Before Es6, the JS language did not have block scope, that is, the scope of {}, only the global scope and function scope, so-called Ascension, that is, the declaration of the variable or function declaration promoted, for example
Console.log (global); Undefinedvar global = 111;console.log (global);//111
Obviously, the above code is in a global scope, using VAR to declare a global variable in that scope, and the actual declaration process is as follows:
var global;console.log (global); Undefinedglobal = 111;console.log (global)//111
It can be seen that the variable declaration of VAR global is promoted to the first line, so the output in the second row is shown as undefined, and the third row is assigned to the global variable;
Therefore, it is important to note that:
1, the declaration of the variable in the scope, will be promoted to the highest level of the function declaration;
2, the need to distinguish between the declaration of variables and the assignment of variables is two different behavior, need to be treated separately;
function Promotion:
There are two ways to create common functions:
1, function declaration;
function func () { ... }
2. Function expression
var func = function () {}
However, only the first function is declared in a way that functions are promoted.
As an example:
Console.log (func ());//1function func () { return 1; }
That is, even if the function is defined after the console, it is raised to the top of the scope, and is higher than the variable promotion.
JS variable promotion and function promotion