recently, reading the "You do not know the JavaScript (roll up)" This book, the book in detail on the many important JavaScript, but often overlooked points, it is highly recommended!!! In the book, the 4th chapter describes the "Ascension," from the example of the process of variable and function promotion, corrected their previous mistakes of understanding (believe that many people understand is wrong)!
We are used to the var a = 2; As a statement, and the JavaScript engine doesn't really think so! Here are a few examples to get you to understand the variable promotion in JavaScript completely!
Example 1:
A = 2;var A; Console.log (a);//2
Example 2:
Console.log (b); Undefinedvar B = 2;
Example 3:
var c;console.log (c);//undefinedc = 2;
Example 4:
Foo (); function foo () {console.log (d);//undefinedvar d = 2;}
Example 5:
Bar ();//typeerrorvar bar = function too () {//...}
Example 6:
Aoo ();//typeerrorboo ();//referenceerrorvar Aoo = function Boo () {//...}
Example 7:
function foo () {console.log (1);} Foo ();//1foo = function () {Console.log (2);};
Example 8:
Foo ();//3function foo () {console.log (1);} var foo = function () {Console.log (2);}; function foo () {console.log (3);}
Example 9:
Foo ();//bvar a = True;if (a) {function foo () {Console.log ("a");}} Else{function foo () {Console.log ("B");}}
Summary:
1. var a = 2, where Var A is in the compile phase, a=2 in the execution phase;
2. Regardless of where the declarations (variables and functions) in the scope appear, they will be processed first before the code itself executes;
3. The declaration itself will be promoted, and the assignment operation, including the assignment of the function expression, will not be promoted;
4. The function is promoted first, then the variable, and the repeating var (variable) declaration is ignored;
5. The following function declaration can overwrite the previous.
PS:
1. The RHS query throws Referenceerror when the required traversal is not found in all nested scopes.
2. RHS queries to a variable, but you try to manipulate it unreasonably (referencing a property in null or undefined type), the TypeError is thrown.
JavaScript promotion (JavaScript you don't know)