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.
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 |
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).