JavaScript Hoisting
JavaScript hoisting is a behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed.
JavaScript Declarations are Hoisted
In JavaScript, a variable can be declared after it has been used.
Example
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
The let and const Keywords
Variables declared using let and const are hoisted to the top of their block scope, but they are not initialized until their declaration is evaluated.
Example
console.log(myVar); // ReferenceError: Cannot access 'myVar' before initialization let myVar = 10;
JavaScript Initializations are Not Hoisted
JavaScript only hoists declarations, not initializations.