Hoisting is JavaScript’s default behavior of moving declarations to the top of their scope before code execution. In practice, it means you can use certain variables and functions before declaring them — but only partially.
Explain 'hoisting' in JavaScript
Use guided tracks for structured prep, then practice company-specific question sets when you want targeted interview coverage.
The Core Idea
Before your code runs, JavaScript’s engine scans the scope and moves declarations (not initializations) to the top. This is called hoisting.
It applies to var variables, function declarations, and class declarations — but with different effects.
Type | Is Hoisted? | Initialized Before Use? | Notes |
|---|---|---|---|
| Yes | No (initialized as | Accessible before declaration, but value is |
| Yes (declared, but in TDZ) | No (ReferenceError if accessed early) | They exist in memory but cannot be accessed before declaration due to the Temporal Dead Zone. |
Function declarations | Yes | Yes | Fully hoisted — can be called before defined. |
Function expressions / arrow functions | No (unless assigned to | No | They behave like normal variables; not callable before definition. |
Example: var Hoisting
A variable declared with var is hoisted to the top of its scope, but only its declaration — not its assignment.
console.log(a); // undefined
var a = 5;
console.log(a); // 5
Under the hood, the code above is interpreted like this:
var a;
console.log(a); // undefined
a = 5;
console.log(a); // 5
Example: let and const Hoisting
Although let and const are hoisted, they live in a special phase called the Temporal Dead Zone (TDZ). You can’t access them until the line where they are declared.
console.log(x); // ❌ ReferenceError
let x = 10;
console.log(x); // ✅ 10
Example: Function Hoisting
Function declarations are fully hoisted, meaning you can call them before they appear in the code.
sayHello(); // ✅ Works fine
function sayHello() {
console.log('Hello!');
}
However, function expressions or arrow functions are not hoisted the same way:
greet(); // ❌ TypeError: greet is not a function
var greet = function() {
console.log('Hi there!');
};
Common Misunderstanding
Hoisting doesn’t move code literally — it’s about how JavaScript’s memory is allocated before execution.
Variables and functions are known to the engine before code runs, which is why you can sometimes access them early.
Think of hoisting like setting the stage before a play:
var= the actor is on stage but asleep (exists, but undefined).let/const= actor is behind the curtain (exists, but unreachable).- Function declaration = actor is fully ready, already rehearsed.
- Function expression = actor hasn’t arrived yet — script will fail if you try to cue them early.
- Declarations (not assignments) are hoisted.
var→ hoisted and initialized asundefined.let/const→ hoisted but in TDZ (can’t access early).- Function declarations → fully hoisted.
- Function expressions → treated as variables, not hoisted safely.