What state is maintained between JavaScript lines?

I was wondering what states persist between the two lines of JavaScript code presented in babel-node . My confusion arises because if you write two lines of code, you can override the definition of a variable without error. For example, using babel-node --presets es2015 you can do:

 > const a = 1; undefined > let a = 2; undefined 

Now, if you write it in one line, you will receive an error message:

 > const a = 1; let a = 2; TypeError: repl: Duplicate declaration "a" ... 

It seems that in the first case, state a is defined as 1 ( const assignment to a variable) is lost (not until the second assignment), and in the second case it is maintained.

What makes the difference here? and what conditions are supported?

+7
javascript ecmascript-6 babeljs
source share
2 answers

Since const and let are new syntaxes, they must be rewritten with the only binding mechanism that was available before ES6: var . In this case, var allows all sorts of random reassignments without any warning.

Therefore, when you enter an expression in babel-node , babel translates it, evaluates it, and then displays the result. Babel can check for improper use of the const binding during forwarding, so you see an error for const a = 1; let a = 2 const a = 1; let a = 2 . But const a = 1 and let a = 2 , when transpiled / are evaluated as separate expressions, will not throw an error, because babel cannot detect the problem in only one expression.


A more vivid demonstration of the problem: for each expr expression, enter babel-node REPL, this is essentially what happens

 evaluate(transpile(expr)) // => someResult 

Thus, you will not see an error here.

 evaluate(transpile('const a = 1')) evaluate('var a = 1') // bind a to 1 // return undefined evaluate(transpile('let a = 2')) evaluate('var a = 2') // bind a to 2 // return undefined 

But you will see an error here.

 evaluate(transpile('const a = 1; let a = 2')) // ERROR during transpile: const a has already been declared 
+6
source share

I do not use babel-repl , but it must have something to do with the conversion that it performs, because everything works as expected with a regular REPL:

 $ node -v v7.4.0 $ node > const a = 1; undefined > let a = 1; SyntaxError: Identifier 'a' has already been declared > const b = 1; let b = 1; const b = 1; let b = 1; ^ SyntaxError: Identifier 'b' has already been declared > .editor // Entering editor mode (^D to finish, ^C to cancel) const c = 1; let c = 1; let c = 1; ^ SyntaxError: Identifier 'c' has already been declared 
+2
source share

All Articles