JavaScript Hoisting
In JavaScript, function and variable declarations are hoisted to the top of the function.
In JavaScript, variables can be declared after they have been used, meaning variables can be used before they are declared.
The following two examples will yield the same result:
Example 1
x = 5; // Set variable x to 5
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
Example 2
var x; // Declare x
x = 5; // Set variable x to 5
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
To understand these examples, you need to understand "hoisting."
Hoisting: Function declarations and variable declarations are silently moved to the top of the function by the interpreter.
JavaScript Initialization is Not Hoisted
JavaScript only hoists declarations, not initializations.
The following two examples will yield different results:
Example 1
var x = 5; // Initialize x
var y = 7; // Initialize y
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y; // Display x and y
Example 2
var x = 5; // Initialize x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y; // Display x and y
var y = 7; // Initialize y
Example 2 outputs undefined for y
, because the variable declaration (var y
) is hoisted, but the initialization (y = 7
) is not, so y
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 an element
elem.innerHTML = x + " " + y; // Display x and y
y = 7; // Set y to 7
Declare Your Variables at the Top
Many programmers are not aware of JavaScript hoisting.
If programmers do not have a good understanding of hoisting, their programs can easily have issues.
To avoid these issues, it is common to declare variables at the beginning of each scope, which is the normal JavaScript parsing step and makes it easier for us to understand.
| | JavaScript strict mode does not allow the use of variables that are not declared. <br>In the next chapter, we will learn about "strict mode." | | --- | --- |