In JavaScript, hoisting is the behavior where variable and function declarations are moved to the top of their scope (before code execution) during the creation phase of the execution context.
Important: Only declarations are hoisted, not initializations.
- Hoisted and initialized to
undefined. - Can be accessed before declaration, but value will be
undefineduntil the line where it's assigned.
console.log(a); // undefined
var a = 10;
console.log(a); // 10Behind the scenes:
var a; // Hoisted declaration
console.log(a);
a = 10;
console.log(a);- Hoisted but not initialized.
- Placed in the Temporal Dead Zone (TDZ) from the start of the block until the declaration line.
- Accessing before declaration → ReferenceError.
console.log(b); // ReferenceError
let b = 20;
console.log(c); // ReferenceError
const c = 30;- Hoisted with the entire function definition.
- Can be called before their declaration.
greet(); // "Hello"
function greet() {
console.log('Hello');
}Behind the scenes:
function greet() {
console.log('Hello');
}
greet();Behavior depends on whether you use var, let, or const.
- Hoisted, but initialized to
undefined. - Calling before assignment → TypeError (because
undefinedis not a function).
sayHi(); // TypeError: sayHi is not a function
var sayHi = function () {
console.log('Hi');
};- Hoisted but in TDZ.
- Calling before declaration → ReferenceError.
sayHi(); // ReferenceError
let sayHi = function () {
console.log('Hi');
};| Declaration Type | Hoisted? | Initialized? | Access Before Decl. |
|---|---|---|---|
| var | Yes | undefined | ✅ undefined |
| let | Yes | No (TDZ) | ❌ ReferenceError |
| const | Yes | No (TDZ) | ❌ ReferenceError |
| Function Declaration (Statement) | Yes | Yes (full fn) | ✅ Works |
| Function Expression (var) | Yes | undefined | ❌ TypeError |
| Function Expression (let/const) | Yes | No (TDZ) | ❌ ReferenceError |
"In JavaScript, hoisting moves variable and function declarations to the top of their scope during the creation phase. Variables declared with var are initialized to undefined, while let and const are hoisted but not initialized, causing a Temporal Dead Zone until declaration. Function declarations are fully hoisted with their definitions, whereas function expressions follow variable hoisting rules."