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

JavascriptScopeEcmascript 6Switch Statement

Javascript Problem Overview


What's the difference between:

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

and

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

At first I thought that I could return an object literal like so, but it turns out it's a syntax error. What's the difference actually?

Example from another question: https://stackoverflow.com/questions/42475118/how-to-pass-switch-statement-as-function-argument-in-javascript-es6/42475344#42475344

Javascript Solutions


Solution 1 - Javascript

Curly braces used in this way establish their own block scope, in which you can define local let variables or const constants:

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

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

The example would throw without nested block scopes, since multiple let/const declarations with the same identifier are not allowed within the same scope in Ecmascript 2015.

Please note that the switch statement creates a block scope itself, i.e. whether you use nested block scopes or not, let/const declarations inside switch don't leak into the parent scope.

However, in the context of switch, curly brackets are also used purely decorative, to visually highlight the blocks of the individual case branches.

Solution 2 - Javascript

you have to use curly brackets:

  1. when creating more block scoped variables (const / let) with the same name
  • according to spec MDN web docs
  • ERROR: Uncaught SyntaxError: Identifier 'variablename' has already been declared
  1. when using eslint in default settings and using even single one (const / let)
  • according to rule no-case-declarations
  • ERROR: Unexpected lexical declaration in case block no-case-declarations

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAurimasView Question on Stackoverflow
Solution 1 - Javascriptuser6445533View Answer on Stackoverflow
Solution 2 - JavascriptMichal Miky JankovskýView Answer on Stackoverflow