JavaScript Hoisting

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

In JavaScript, a variable can be declared after it has been used; in other words, a variable can be used before it is declared.

The following two examples will get 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; // Declare x

Try it Yourself »

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 Yourself »

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

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


JavaScript Initializations Are Not Hoisted

JavaScript initializations are not hoisted. In JavaScript, only the variable declarations are hoisted, not the initializations.

The following two examples do not get the same result:

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 Yourself »

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; // Initialize y

Try it Yourself »

In Example 2, y outputs undefined,undefinedThis is because the variable declaration (var y) is hoisted, but the initialization (y = 7) is not hoisted, so the y variable is an undefined variable.

Example 2 behaves like 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 do not know about JavaScript hoisting.

If programmers do not have a good understanding of hoisting, the programs they write are prone to errors.

To avoid these problems, we usually declare these variables at the beginning of each scope. This is also the normal JavaScript parsing step, making it easier to understand.

Note JavaScript strict mode does not allow undeclared variables to be used.
In the next chapter, we will learn about"strict mode" 。
Other Extensions