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: How to pass switch statement as function argument in Javascript ES6?
you have to use curly brackets:
const
/let
) with the same nameconst
/let
)Curly braces used in this way establish their own block scope, in which you can define local
let
variables orconst
constants: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 insideswitch
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 individualcase
branches.