JavaScript Variable Promotion


In JavaScript, the declaration of functions and variables will be promoted to the top of the function.

In JavaScript, variables can be declared after use, that is, variables can be used first and then declared.

The following two examples will achieve the same result:

Example 1

x = 5; // variable x is set to 5

elem = document.getElementById("demo"); // find element
elem.innerHTML = x; // display x in the element

var x; // declare x

 Try It!


Example 2


var x; // declare x
x = 5; // variable x is set to 5

elem = document.getElementById("demo"); // find element
elem.innerHTML = x; // display x in the element

Try It! 

To understand the above examples, you need to understand "hoisting".

Declaration promotion: Function declarations and variable declarations are always quietly "lifted" to the top of the method body by the interpreter.


JavaScript Initialization Will Not promote

In JavaScript, only declared variables will be promoted, not initialized ones.

The results of the following two examples are not the same:

Example 1

var x = 5; // initialize x
var y = 7; // initialize y

elem = document.getElementById("demo"); // find element
elem.innerHTML = x + "" + y; // display x and y

 Try It! 

Example 2


var x = 5; // initialize x

elem = document.getElementById("demo"); // find element
elem.innerHTML = x + "" + y; // display x and y

var y = 7; // initialize y

 Try It! 

The y of Example 2 outputs undefined because the variable declaration (var y) is promoted, but the initialization (y = 7) will not be promoted, so the y variable is an undefined variable.

Example 2 is similar to the following code:

var x = 5; // initialize x
var y; // declare y

elem = document.getElementById("demo"); // find element
elem.innerHTML = x + "" + y; // display x and y

y = 7; // set y to 7

Declare Your Variables At The Head

For most programmers, JavaScript declaration promotion is not known.

If programmers don't understand declarative promotion well, the programs they write are prone to some problems.

In order to avoid these problems, we usually declare these variables before the start of each scope. This is also a normal JavaScript parsing step, which is easy for us to understand.

NoteJavaScript strict mode (strict mode) does not allow the use of undeclared variables.
We will learn about "strict mode" in the next chapter .