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
4 Replies
John
John3y ago
I’d use objects instead of switch tho
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
iMagic
iMagicOP3y ago
Yup. If we're following regular JS scoping rules it makes sense to me why i would get a reference error there. That second example was just delving deeper into this
(which i wasnt expecting to be able to do anyway, but if i did it would at least make sense)
I guess what my post boils down to ultimately is why i wouldnt be able to define variables under the same name across different cases
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
Want results from more Discord servers?
Add your server