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).
This post was published 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.