JavaScript Hoisting
- Previous Page JS Scope
- Next Page JS Strict Mode
Hoisting is the default behavior of JavaScript that moves declarations to the top.
JavaScript declarations are hoisted
In JavaScript, variables can be declared after they are used.
In other words, it can be used before the variable is declared.
Example 1 WithExample 2 The results are the same:
Example 1
x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find the element elem.innerHTML = x; // Display x in the element var x; // Declare x
Example 2
var x; // Declare x x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find the element elem.innerHTML = x; // Display x in the element
To understand this, you must understand the term 'hoisting'.
Hoisting is the default behavior of JavaScript that moves all declarations to the top of the current scope (to the top of the current script or the top of the current function).
the let and const keywords
using let
or const
Declared variables and constants are not hoisted!
Please visit JS Let / Const Read more about let and const in this section.
JavaScript initializations are not hoisted
JavaScript only hoists declarations, not initializations.
Example 1 WithExample 2 The results are not the same:
Example 1
var x = 5; // Initialize x var y = 7; // Initialization of y elem = document.getElementById("demo"); // Find the element elem.innerHTML = x + " " + y; // Display x and y
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; // Initialization of y
Can the last example's y still be undefined?
This is because only the declaration (var y) rather than the initialization (=7) is hoisted to the top.
Due to hoisting, y has been declared before it is used, but since the initialization has not been hoisted, the value of y is still undefined.
Example 2 is the same:
Example
var x = 5; // Initialize x var y; // Declare y elem = document.getElementById("demo"); // Find the element elem.innerHTML = x + " " + y; // Display x and y y = 7; // Assign 7 to y
Declare your variables at the top!
Hoisting (to many developers) is an unknown or ignored behavior in JavaScript.
If developers do not understand hoisting, the program may contain bugs (errors).
To avoid bugs, always declare all variables at the beginning of each scope.
Since this is the way JavaScript interprets code, please maintain this good habit.
Strict mode in JavaScript does not allow the use of variables without declaration.
Please learn more in the next chapter “use strict"
- Previous Page JS Scope
- Next Page JS Strict Mode