1

I am glad JavaScript has the new let statement to declare a block scope local variable. However, there appears to be a type error when declaring to let variables in a switch statement, which would be a very useful scenario to use let.

function test(x) { 
  'use strict';
  switch (x) {
    case 0:
      let foo;
      break;

    case 1:
      let foo; // TypeError for redeclaration.
      break;
  }
}

Sure enough, MDN shows this example:

You may encounter errors in switch statements because there is only one underlying block.

So why is a switch statement only one underlying block?

styfle
  • 22,361
  • 27
  • 86
  • 128
  • You can't have 2 `foo`'s in the same block. – 001 Nov 19 '15 at 18:51
  • 2
    @JohnnyMopp I'm not sure you read my question. – styfle Nov 19 '15 at 18:52
  • http://stackoverflow.com/questions/2524397/what-is-the-javascript-variable-scope-in-a-switch-case-statment – Marc B Nov 19 '15 at 18:53
  • [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block): _A block statement ... is used to group zero or more statements. **The block is delimited by a pair of curly brackets.**_ – 001 Nov 19 '15 at 18:56
  • @MarcB Thanks for the similar question. It's not quite the same since it was asked before `let` and the answer says "Javascript does not use block scope." which is not true. – styfle Nov 19 '15 at 20:02
  • @JohnnyMopp Thanks. It looks like mcfedr answered with an example using curly brackets that works well. – styfle Nov 19 '15 at 20:03
  • Also relevant for [C# switch scope](http://stackoverflow.com/q/3652408/266535). Looks like the same behavior. – styfle Nov 19 '15 at 20:10

1 Answers1

3

Basically comes down to down to how switches work, and its expressed in the syntax that it has only one pair of {}

Because of how you can fall though from one case to the other by missing out break - in that case you would want to have the same scope.

You can put an extra {} around you case:

switch(a) {
    case 1:{
        let a = 1;
    }
}

This is the case is most c-ish languages with block scope.

mcfedr
  • 7,845
  • 3
  • 31
  • 27