Variable ascension

The way a JavaScript engine works is it parses the code, gets all the declared variables, and then runs them line by line. The result is that all variable declarations are promoted to the top of the code, which is called variable promotion.

Example:

console.log(a) // undefined

var a = 1

function b() {
    console.log(a)
}
b() // 1
Copy the code

The actual order of execution of the above code looks like this:

Var a = undefined; var a = undefined; var a = undefined;

var a = undefined
console.log(a) // undefined

a = 1

function b() {
    console.log(a)
}
b() // 1
Copy the code

The second step is execution, so the JS engine runs the current result line by line from top to bottom, which is called variable promotion.

Statement of ascension

Declarations in the current scope are promoted to the top of the scope, including declarations of variables and functions

(function(){ var a = "1"; var f = function(){}; var b = "2"; var c = "3"; }) ();Copy the code

The declaration of variables a,f,b,c is promoted to the top of the function scope, like this:

(function(){ var a,f,b,c; a = "1"; f = function(){}; b = "2"; c = "3"; }) ();Copy the code

Note that function expressions are not promoted, which is the difference between function expressions and function declarations. Take a closer look at the differences:

(function(){ //var f1,function f2(){}; // apply as an implicit promotion claim f1(); //ReferenceError: f1 is not defined f2(); var f1 = function(){}; function f2(){} })();Copy the code

The function declaration f2 is promoted in the above code, so it is ok to call F2 earlier. Although the variable f1 is also promoted, the promoted value of f1 is undefined, whose true initial value is given at the execution point of the function expression. So only statements are promoted.