Hoisting in JavaScript
🤔 What is Hoisting?
Hoisting is JavaScript's default behavior of moving declarations (not initializations) to the top of their containing scope during the compilation phase. It applies to both var, function, and (to some extent) let and const.
Note
Only declarations are hoisted — initializations stay in place!
📦 Variable Hoisting
var Example
console.log(a); // undefined
var a = 10;This works because var a is hoisted to the top as:
Code Snippet
var a;
console.log(a); // undefined
a = 10;Note
let and const are hoisted too, but placed in the temporal dead zone (TDZ), meaning they cannot be accessed before their declaration.
let Example
console.log(b); // ❌ ReferenceError
let b = 20;🔧 Function Hoisting
Function declarations are fully hoisted — you can call them before they're defined.
Code Snippet
greet(); // ✅ Hello
function greet() {
console.log("Hello");
}But function expressions and arrow functions are not hoisted the same way.
Code Snippet
sayHi(); // ❌ TypeError: sayHi is not a function
var sayHi = function () {
console.log("Hi");
};🎯 Summary
- var is hoisted and initialized to undefined.
- let and const are hoisted but not initialized — they exist in the TDZ.
- Function declarations are fully hoisted.
- Function expressions and arrow functions are not hoisted like declarations.
>>“Hoisting doesn't move code — it moves declarations during compile time.”