Why Does This Happen?
If you specify the same variable name (created using let
, const
or var
) 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).
How to Fix the Issue?
To fix this issue, you can do either of the following:
- Consider not using the same variable names in
case
/default
clauses (to avoid confusion and variable name collision), or; - Wrap each
case
/default
clause with curly braces ({}
).
For example, you can wrap each case
/default
clause with curly braces ({}
), 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 block scope, preventing issues with variable shadowing.
This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.