function switchCaseWarn(arg) {
switch(arg) {
case 'A':
let name = 'Apple';
break;
case 'J':
let name = 'Jackfruit';
break;
}
}
Line 7: Duplicate declaration "name"
At any given time only one case statement will be executed and therefore name is not likely to be duplicated.
Is the warning accurate? I imagine every case block has its own scope and variable declared inside it cannot leak to outer scope. Or am I missing something?
switch statements introduce a new block scope around the whole switch body (the curly brackets). There no block scope introduced by individual case statements. Imagine for instance:
function switchCaseWarn(arg) {
switch(arg) {
case 'A':
let name = 'Apple';
case 'J':
let name = 'Jackfruit';
break;
}
}
would be invalid because let name is declared twice.
You can however add new block scopes by adding your own {}s manually if you want, just like you can anywhere else:
function switchCaseWarn(arg) {
switch(arg) {
case 'A': {
let name = 'Apple';
break;
}
case 'J': {
let name = 'Jackfruit';
break;
}
}
}
Ok! Thanks!
Most helpful comment
switch statements introduce a new block scope around the whole switch body (the curly brackets). There no block scope introduced by individual
casestatements. Imagine for instance:would be invalid because
let nameis declared twice.You can however add new block scopes by adding your own
{}s manually if you want, just like you can anywhere else: