Before ES6, JavaScript had no block-level scope (a pair of curly braces {} is a block-level scope), with only global scope and function scope. The variable elevation is about to elevate the variable declaration to the beginning of the scope where it is located. A simple example such as:
Console.log (a); Undefinedvar a= ' Hello '; console.log (hello); Hello function fn () {console.log (b);//undefined var b = ' BBB '; Console.log (b); BBB}FN ();
The reason is that the above printing results, is due to JS variable promotion, in fact, the above code is executed according to the following:
var A; Variable promotion, global scope, at this time only declaration, and no assignment console.log (a); Undefineda= ' AAA '; The value of Console.log (a) is only assigned at this time; Print out global function fn () {var b;//variable elevation, function scope Console.log (b); b = ' BBB '; Console.log (b);} FN ();
Precautions :------- There are no variable-promoted variables
varA "variable elevation" behavior occurs when a variable can be used before a declaration, with a value of undefined . This kind of phenomenon is somewhat strange, according to the general logic, the variable should be used after declaring the statement.
In order to correct this phenomenon, the let command changes the syntax behavior, it declares the variable must be used after the declaration, otherwise error.
The case of Var console.log (foo); Output Undefinedvar foo = 2;//Let case console.log (bar); Error Referenceerrorlet bar = 2;
constThe constant of the command declaration is also not elevated, and there is also a temporary dead zone that can only be used after the declared location.
if (true) { console.log (MAX);//referenceerror const MAX = 5;}
Second, function promotion
There are two ways to create functions in JS: function declarations and function literals. function promotion only exists for function declarations! Such as:
Console.log (F1); Function F1 () {} Console.log (F2);//undefined function F1 () {}var F2 = function () {}
Only so will have the above print result, is because the function promotion in JS causes the code to actually execute according to the following:
Function F1 () {}//functions promoted, entire code block promoted to the beginning of file <br> Console.log (F1); Console.log (F2); var F2 = function () {}
Conclusion: Basically this is the case, to master the words can do more exercises, test:
Console.log (F1 ()); Console.log (F2); Function F1 () {console.log (' AA ')}var F2 = function () {}
(function () {console.log (a); A = ' AAA '; var a = ' BBB '; Console.log (a);}) ();
In-depth understanding of JS's variable elevation and function promotion