Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const already declared in ES6 switch block [duplicate]

Consider the file sample.es6

switch (1) {     case 1:         const foo = 1;         break;     case 2:         const foo = 2;         break; } 

If I run it with Node I got

$ node --version v4.2.11 $ node sample.es6  /tmp/sample.es6:6 const foo = 2; ^  SyntaxError: Identifier 'foo' has already been declared     at Object.<anonymous> (/tmp/sample.es6:1:11)     at Module._compile (module.js:435:26)     at Object.Module._extensions..js (module.js:442:10)     at Module.load (module.js:356:32)     at Function.Module._load (module.js:311:12)     at Function.Module.runMain (module.js:467:10)     at startup (node.js:134:18)     at node.js:961:3 

Why I'm getting this error? Node shouldn't evaluate const foo = 2;.

like image 706
Raniere Silva Avatar asked Oct 28 '15 17:10

Raniere Silva


2 Answers

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.

like image 186
Hinrich Avatar answered Sep 23 '22 14:09

Hinrich


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.

like image 37
Igor Raush Avatar answered Sep 21 '22 14:09

Igor Raush