Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during compilation, before code execution.
- Only declarations are hoisted, not initializations.
- It applies differently to
var,let,const, and functions.
🔹 Example with var
console.log(a); // undefined (declaration hoisted, value not)
var a = 5;
console.log(a); // 5
What actually happens behind the scenes:
var a; // declaration hoisted
console.log(a); // undefined
a = 5; // initialization
console.log(a); // 5
🔹 Example with let and const
console.log(b); // ❌ ReferenceError
let b = 10;
console.log(c); // ❌ ReferenceError
const c = 15;
- Variables declared with
letandconstare hoisted but remain in a Temporal Dead Zone until initialized.
🔹 Example with Functions
greet(); // "Hello!"
function greet() {
console.log("Hello!");
}
// Function declarations are fully hoisted
- Function expressions are not hoisted fully:
sayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function() {
console.log("Hi");
};
✅ Key Points
- Declarations move to the top of their scope.
var→ hoisted + initialized toundefinedlet&const→ hoisted but uninitialized (Temporal Dead Zone)- Function declarations → fully hoisted
- Function expressions → hoisted like variables
Hoisting explains why some variables/functions can be used before their actual declaration in code.