If you specify the same variable name (created using let
or const
) within case
/default
in a switch
statement, then it may result in a SyntaxError
(as shown in the example below):
const type = 2;
switch (type) {
case 1:
let foo = 'bar';
console.log(foo);
break;
case 2:
// SyntaxError: Identifier 'foo' has already been declared
let foo = 123;
console.log(foo);
break;
// ...
}
This happens because:
let
andconst
cannot be shadowed in a local scope, and;case
/default
clauses share the same scope (as defined by their containingswitch
statement).
To fix this, you should first of all consider not using the same variable names in case
/default
clauses (to avoid confusion). If you must use them, then you could simply wrap each case
/default
clause with curly braces ({}
), for example, like so:
// ES6+ const type = 2; switch (type) { case 1: { let foo = 'bar'; console.log(foo); break; } case 2: { let foo = 123; console.log(foo); break; } // ... } // output: 123
This will give each case
/default
its own scope, preventing issues with variable shadowing.
Hope you found this post useful. It was published . Please show your love and support by sharing this post.