What do the braces in the switch statement do after the case in es6?

What's the difference between:

switch (expression) { case: somethings; break; } 

and

 switch (expression) { case: { somethings; break; } } 

At first it seemed to me that I could return an object literal like that, but I got a syntax error. What is the difference really?

An example from another question: How to pass a switch statement as an argument to a function in Javascript ES6?

+11
source share
2 answers

The curly braces used in this way set their own block area, in which you can define local let variables or const :

 switch (false) { case true: { let x = "bar"; console.log(x); break; } case false: { let x = "baz"; console.log(x); break; } } 

The example will be thrown without nested blocks, since multiple let / const declarations with the same identifier are not allowed within the same scope in Ecmascript 2015.

Note that the switch creates the scale of the block itself, that is, regardless of whether you use nested areas of the block or not, let / const declarations inside the switch do not leak into the parent area.

However, in the context of a switch curly braces are also used exclusively decoratively to visually highlight blocks of individual case branches.

+35
source

You should use braces:

  1. when creating more block region variables ( const / let ) with the same name
    • according to the MDN Web Docs specification
    • ERROR: Uncaught SyntaxError: Identifier 'variable name' already declared
  2. when using eslint in the default settings and using even one ( const / let )
    • according to the no-case declaration rule
    • ERROR: unexpected lexical declaration in case of block
0
source

Source: https://habr.com/ru/post/1264767/