In JavaScript, hoisting is not magic—it’s the engine preparing the stage before your code begins to speak. Declarations rise to the top of their scope, while assignments stay where they are. That subtle difference is where most confusion is born.
Let’s walk through it like a craftsman, piece by piece.
1. Variable Hoisting (var)
console.log(a); // undefined
var a = 10;
console.log(a); // 10
What actually happens behind the curtain:
var a; // hoisted declaration
console.log(a); // undefined
a = 10; // assignment stays here
console.log(a); // 10
Truth:
varis hoisted and initialized withundefined- That’s why it doesn’t crash—it just feels… incomplete
2. Let & Const Hoisting (Temporal Dead Zone)
console.log(b); // ❌ ReferenceError
let b = 20;
Reality:
letandconstare hoisted- But they are not initialized
- They live in something called the Temporal Dead Zone (TDZ)
Behind the scenes:
// b is hoisted but not initialized
console.log(b); // ❌ can't access before initialization
let b = 20;
Truth:
- Access before declaration = error, not undefined
- Cleaner, safer, less forgiving
3. Function Hoisting (Function Declaration)
greet(); // Works perfectly
function greet() {
console.log("Hello, Warrior!");
}
Behind the scenes:
function greet() {
console.log("Hello, Warrior!");
}
greet(); // WorksTruth:
- Function declarations are fully hoisted
- You can call them before they appear
4. Function Expression (Not Fully Hoisted)
sayHi(); // ❌ TypeError
var sayHi = function() {
console.log("Hi!");
};
What really happens:
var sayHi; // hoisted (undefined)
sayHi(); // ❌ undefined is not a function
sayHi = function() {
console.log("Hi!");
};Truth:
- Variable is hoisted
- Function is not ready yet
5. Arrow Function Hoisting
hello(); // ❌ TypeError
const hello = () => {
console.log("Hello!");
};
Truth:
- Same as
let/const - Not initialized → lives in TDZ
Final Reality Check
Hoisting is not lifting your code—it’s reordering how the engine reads it.
Golden Rules:
var→ hoisted + initialized (undefined)let/const→ hoisted but stuck in TDZfunction declaration→ fully hoistedfunction expression→ behaves like variables
One Real-World Analogy
Think of JavaScript execution like preparing a classroom:
- Function declarations → teacher already present before class starts
- var variables → chairs are placed but empty
- let/const variables → chairs are reserved but locked until time
Try sitting before time—you’ll be thrown out (ReferenceError).

Leave a Reply