iMagic
iMagic
TTCTheo's Typesafe Cult
Created by iMagic on 11/26/2022 in #questions
Is this intended JS behavior?
Came across this problem when using switch statements. Doesnt seem like each case has its own scope, however, you cannot access a variable outside of the case it was defined in (which i wasnt expecting to be able to do anyway, but if i did it would at least make sense) despite not being able to share variable names from case to case. Take the following example
function test() {
const test = "testvar";

switch (test) {
case "testvar":
const otherTest = "result";
break;

case "test":
const otherTest = "resultTwo"; // SyntaxError: Identifier 'otherTest' has already been declared
break;
}
}
function test() {
const test = "testvar";

switch (test) {
case "testvar":
const otherTest = "result";
break;

case "test":
const otherTest = "resultTwo"; // SyntaxError: Identifier 'otherTest' has already been declared
break;
}
}
This also errors out
function test() {
const test = "testvar";

switch (test) {
case "testvar":
const otherTest = "result";
break;

case "test":
const otherTestNew = "resultTwo";
break;
}

console.log(otherTest); // ReferenceError: otherTest is not defined
}
function test() {
const test = "testvar";

switch (test) {
case "testvar":
const otherTest = "result";
break;

case "test":
const otherTestNew = "resultTwo";
break;
}

console.log(otherTest); // ReferenceError: otherTest is not defined
}
I understand that a let variable can just be made outside of the switch statement and then be mutated across each case but i just found this behavior very interesting
9 replies