JavaScript Variable Declaration Promotion
The part of the variable promotion is just the declaration of the variable, and the assignment statement and the executable code logic remain in place.
Second, in the basic statement (or code block) (such as: if statement, for statement, while statement, switch statement, for...in statement, etc.), there is no variable declaration promotion
The function declaration is promoted, but the function body of the function expression is not promoted
1Fun ();//Hello2 functionFun () {3Console.log ("Hello");4 }5 // --------------6 //after promotion7 8 functionFun () {9Console.log ("Hello");Ten } One AFun ();//Hello
1 varFun =function(){2Console.log ("Hello");3 };4 5 // --------------6 //after promotion7 8 varFun ;9 TenFun ();//error, Typeerror:fun is not a function One AFun =function(){ -Console.log ("Hello"); -};
If a variable has the same name as a function, the function declaration takes precedence over the declaration of the variable (after all, the function is the first class of JavaScript), and a variable declaration with the same name as the function names will be ignored
Look at a few examples:
The first one:
1 var foo = 1; 2 function Bar () { 3 if (! foo) { 4 var foo = 10; 5 6 alert (foo); // output is 7 8 bar ();
The
In the If statement (in JavaScript cannot call the Block bar ~ ~ ~), the variable will not be promoted, so!foo evaluates to true, so the output is 10.
. r> Second:
1 var a = 1; 2 function B () {3 a = ten; 4 return ; 5 function A () {} 6 }7B (); 8 alert (a); // 1
This is a magical question. At first glance, the output is 10. But, according to the fourth sentence, you can get:
1 function B () {2 function A () {};// variable elevation 3 a = ten; 4 return ; 5 }
function A () {} is defined in the same way as var a = function () {}. So, you can get:
1 varA = 1;//defines "a" in global scope2 functionB () {3 varA =function() {};//defines "a" in local scope4A = 10;//overwrites local variable "a"5 return; 6 } 7 b (); 8alert (a);//Alerts global variable "a"
1 var a=1; 2 (function() {3 a=2;b=2; 4 5 })(); 6 alert (a==b); // true, the scope of the problem, there is the difference between Var and no Var ~
JavaScript Variable Declaration Promotion