JavaScript only hoists declarations, not initializations.
Therefore, Example 1 does not produce the same result as Example 2.
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 |
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 |
Yes, it makes sense that y
is undefined because only the declaration (var y
) is hoisted, not the initialization (= 7
), leaving its value undefined until assigned.
Example 2 is equivalent to writing:
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; // Assign 7 to y |
Hoisting in JavaScript can lead to bugs if overlooked. To avoid this, it’s best to declare all variables at the start of each scope, aligning with JavaScript’s interpretation of code.
In strict mode, JavaScript prevents the use of variables that have not been declared. You will learn more about “use strict” in the next chapter. |