Upgrade JavaScript (JavaScript you Don't know) to improve javascript
Recently, I have read the book "JavaScript (on-volume) You don't know", which details many important but often overlooked JavaScript points. I strongly recommend this book !!! In the book, Chapter 1 describes "Upgrade", describes the process of variable and function upgrade from the example, and corrects the previous misunderstanding (I believe many people understand it as a mistake )!
We are used to regard var a = 2; as a declaration, but in fact the JavaScript engine does not think so! The following examples help you fully understand how to improve the variables in JavaScript!
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; var a is in the compilation phase, and a = 2 is in the execution phase;
2. No matter where the Declaration (variables and functions) in the scope appear, they will be processed before the Code itself is executed;
3. the Declaration itself will be promoted, while the assignment operations, including the assignment of function expressions, will not;
4. The function will be promoted first, and then the variable. Repeated var (variable) declarations will be ignored;
5. The subsequent function declaration can overwrite the previous one.
PS:
1. A ReferenceError will be thrown if the RHS query fails to find the required traversal in all nested scopes.
2. RHS will query a variable, but you will throw a TypeError if you try to operate it unreasonably (reference a property of the null or undefined type.