Starting with ES6, you may use curly braces ({}
) with the case
/default
clauses in a switch
statement. This allows you to create a block-scope for case
and default
, so that you can define local let
or const
(relative to that block). For example:
// 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
As you can see from the example above, using curly braces ({}
) creates a block-scope for case
(and default
). This allows you to use the same variable names in each block (which would have otherwise thrown a SyntaxError
).
Hope you found this post useful. It was published . Please show your love and support by sharing this post.