Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JS Hoisting

JavaScript Declarations are Hoisted

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

In other words, you can reference a variable even if its declaration appears later in the code.

Example 1 produces the same result as Example 2.

Example 1

x = 5// Assign 5 to x

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// Assign 5 to x

elem = document.getElementById(“demo”); // Find an element
elem.innerHTML = x;                     // Display x in the element

To grasp this concept, you need to understand “hoisting.”

Hoisting is JavaScript’s default behavior of moving all declarations to the top of their respective scope (either the top of the current script or function).