Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

JavaScript Hoisting

JavaScript Hoisting

In JavaScript, declarations of functions and variables are hoisted to the very top of the function.

In JavaScript, a variable can be declared after it is used, that is, a variable can be used before it is declared.

The following two examples will produce the same result:

Example 1

x = 5; // set variable x to 5

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

var x; // 声明 x 

Try it »

Example 2

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

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

Try it »

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

Hoisting: function declarations and variable declarations are always silently "hoisted" by the interpreter to the very top of the method body.


JavaScript Initialization Is Not Hoisted

JavaScript initialization is not hoisted; in JavaScript only the declared variable part is hoisted, the initialization part is not.

The following two examples produce different results:

Example 1

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

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

Try it »

Example 2

var x = 5; // initialize x

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

 var y = 7; // 初始化 y 

Try it »

In Example 2, y outputs undefined, because the variable declaration (var y) is hoisted, but the initialization (y = 7) is not, so the y variable 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 at the Top

Most programmers are not aware of JavaScript hoisting.

If programmers do not understand hoisting well, the programs they write are prone to some problems.

To avoid these problems, we usually declare these variables at the beginning of each scope, which is also the normal JavaScript parsing step and is easier for us to understand.

| Note | JavaScript strict mode does not allow the use of undeclared variables.
In the next chapter we will learn about "strict mode" 。 | | --- | --- |