const already declared in ES6 switch block [duplicate] const already declared in ES6 switch block [duplicate] node.js node.js

const already declared in ES6 switch block [duplicate]


You can create scope blocks around your cases, and the compiler will be happy:

switch (1) {    case 1: {        // notice these extra curly braces        const foo = 1;        break;    }    case 2: {        const foo = 2;        break;    }}

Read the answer from Igor if you need more context.


You are getting a SyntaxError because you are re-declaring a variable in the same scope; a switch statement contains only one underlying block, rather than one block per case.

JavaScript throws the error at compile time. "Node shouldn't evaluate const foo = 2;" is irrelevant because this error occurs before Node evaluates anything.

One purpose of const (and a lot of new ES6 features, for example the new module spec) is to enable the compiler to do some static analysis. const tells the compiler that the variable will never be reassigned, which allows the engine to handle it more efficiently.

Of course, this requires a compile-time check to make sure the variable is indeed never reassigned (or redeclared), which is why you are seeing the error.


You can use Immediately Invoked Function Expression (IIFE) for const assignment:

const foo=(function(){  switch (1) {    case 1:      return 1;      break;    case 2:      return 2;      break;  }})();console.log('foo = '+foo); /* foo = 1 */

Altenatively, you can create a scope inside the case with curly braces, but you cannot access the foo outside switch block :

switch (1) {  case 1: {    const foo = 1;    console.log(foo+' from inside'); /* 1 from inside */  } break;  case 2: {    const foo = 2;    console.log(foo+' from inside');  } break;}console.log(foo+' from outside'); /* foo is not defined */