JS variable promotion


First, let’s look at the rules of variable promotion

    1.Variable declaration and function declaration will be promoted to the top of scope;

    2.When the same name appears, the priority is: variable declaration < function declaration < variable assignment

 Here’s an example:

var foo =function(x, y){
   return x - y;
function foo(x, y){
   return x + y;
var num = foo(1, 2);

At first glance, the result should be 3. The function with the same name after overwrites the previous function. In fact, this is caused by variable promotion. Let’s look at the actual running order of the code in the JS compiler, and then you can see the rules.

//Rule 1, all variable declarations and function declarations refer to the top of the scope
var foo;//foo#1
var num;
//Rule 2 so function declaration follows variable declaration
function foo(x, y){//foo#2
   return x + y;
//Function function expressions are not promoted
foo =function(x, y){//foo#3
   return x - y;
Num = foo (1, 2); // variable assignment
//The higher the priority, the lower the order of the JS compiler, and the value of the same name is followed by the value of the previous one.

Thus, the address represented by the foo variable finally points to the memory of the subtraction function. So the execution result is – 1 instead of 3. After reading this example, you must know what variable promotion is.