JavaScript variable lift

JavaScript, the function and the variable declaration will be raised to the top of the function.

JavaScript, variables can be declared after use, that is, variables can be declared before the first use.

The following two examples will get the same result:

Example 1

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

elem = document.getElementById ( "demo") ; // Find element
elem.innerHTML = x; // X is displayed in the element

var x; // declare x


Example 2

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

elem = document.getElementById ( "demo") ; // Find element
elem.innerHTML = x; // X is displayed in the element

To understand the above examples you need to understand "hoisting (variable lift)."

Variable Lift: function declarations and variable declarations will always be the interpreter quietly been "promoted" to the top of the method body.


JavaScript initialization will not improve

JavaScript variable declarations will only increase, not initialized.

Results 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 the x and y


Example 2

var x = 5; // initialize x

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

var y = 7; // initialize y

Y Example 2 is outputundefined, this is because the variable declaration (var y) has improved, but the initialization (y = 7) does not increase, so the variable y is an undefined variable.

Example 2 is similar to the following code:

var x = 5; // 初始化 x
var y;     // 声明 y

elem = document.getElementById("demo"); // 查找元素
elem.innerHTML = x + " " + y;           // 显示 x 和 y

y = 7;    // 设置 y 为 7

Declare your variables in the head

For most programmers do not know JavaScript variable lift.

If the programmer is not well understood variables to enhance their written procedures prone to some problems.

To avoid these problems, we usually declare these variables before the beginning of each scope, this is normal JavaScript parsing step, easy to understand us.

Note JavaScript strict mode (strict mode) is not allowed to use an undeclared variable.
In the next chapter we will learn to "strict mode (strict mode)".