Recently studying ES6 in the ES6 series with Nanyi, some errors were found in the Let and Const commands chapter, which lists
First, let does not exist the variable promotion assumes that there is no variable promotion, then in the Ruan Feng article this code code is correct
function do_something () { console.log (foo);//Referenceerror let foo = 2;}
The program will report referenceerror errors, while the actual execution is Undefinedg:\phpdemo\system\content\js>babel-node test.js
Undefined then we look at a piece of code, because there is a variable promotion, the following line of code will output undefined
Console.log (x); var x=5;
And the same code below will output the undefined
Console.log (x); let x=5;
We can see that let's do the variable promotion, and then we'll take a look at a sample code copied from the Nanyi ES6 series to see http://es6.ruanyifeng.com/#docs/let
if (true) { ///TDZ start tmp = ' abc ';//Referenceerror Console.log (TMP);//Referenceerror let tmp;//Tdz End C4/>console.log (TMP); Undefined tmp = 123; Console.log (TMP); 123}
The code after compiling the code through Babel to ES5 is as follows:
' Use strict '; if (true) { ///TDZ start _tmp = ' abc ';// Console.log (_TMP);//ABC var _tmp = undefined;//TDZ End Console.log (_tmp);//undefined _tmp = 123; Console.log (_TMP); 123}
Not the output referenceerror these errors, and we see that the actual compilation situation is let tmp into the Var _tmp=undefined, which proves that the nature of the let compile is var declared variable, since it is VAR declared variable, Then there is bound to be a variable promotion. Then we change this code, add a global variable to the outside of the TMP as follows:
var tmp= ' Dev '; if (true) { console.log (TMP); let TMP; Console.log (TMP); TMP = 123; Console.log (TMP);}
Will this code output dev,undefined,123 or will it output referenceerror,undefined,123? But it's not, actually, what he's really exporting is Jiangzi undefined,undefined, 123 and then we'll look at the generated ES5 code.
' Use strict '; var tmp = ' dev '; if (true) { console.log (_tmp); var _tmp = undefined; Console.log (_tmp); _tmp = 123; Console.log (_tmp);}
Gee, in the block-level scope, it declares that let is essentially declaring a new variable to dominate its own block-level scope, and you cannot enter my territory outside of the "Same variable" (ES6). Finally, let's get to the bottom of the list. 1. Allowed has block-level scope 2, a let in the block-level scope of the variable promotion 3, not in the same scope (function scope and block-level scope) with let declare the same variable PS: As a lot of books and related articles about ES6 are in ES6 before the official release of the early adopters, inevitably there will be some mistakes, so the reference book at the same time is a lot of hands-on practice as well, do not drop the pit
Variable declaration promotion in ES6