Explain it simply
Explain it simply
Imagine the chair of a meeting reading the attendance list before the meeting starts. Everyone on the list is known to exist, even if they have not walked into the room yet. JavaScript does something similar: before running a scope, it first registers every declaration in it (var, let, const, function, class). This is called hoisting.
But being on the list is not the same as being ready. A function declaration is fully ready, a var waits with the value undefined, and let and const cannot be touched at all until their own line runs.
Problem → Why → Solution
The problem: the price becomes NaN with no error
In the code below, a developer moved the line that applies the discount towards the top of the file. Because discountRate was declared with var, JavaScript does not raise an error: it quietly uses undefined, and the price becomes NaN. With no error message, that NaN can travel all the way to the checkout page.
const price = 200;
const finalPrice = price - price * discountRate; // runs first
var discountRate = 0.1; // declared later in the file
console.log(finalPrice); // NaN — no error, just a wrong numberWhy is there no error?
var discountRate is hoisted, so the variable exists from the start of the file with the value undefined. 200 * undefined is NaN, and subtracting NaN still gives NaN. Declared with let or const instead, line 2 would throw the ReferenceError "Cannot access 'discountRate' before initialization" and you would see the bug immediately.
Core concept: the creation phase and the execution phase
Hoisting is often described as "moving declarations to the top of the scope", but no line of code actually moves. When a function (or a script, module or block) runs, the engine works in two phases. In the creation phase it sets up a binding, a slot linking a name to a value, for every declaration in that scope. Only in the execution phase does it run the code line by line, top to bottom.
Each kind of declaration leaves the creation phase in a different state. A function declaration is bound together with its whole body, so you can call it above its line. A var is initialised to undefined, so an early read returns undefined without an error. let, const and class get a binding that is not initialised yet. The stretch from the start of the scope to the declaration line is the temporal dead zone (TDZ), and any read or write inside it throws a ReferenceError.
| Declaration | Used before its line | Scope |
|---|---|---|
| function name() {} | Works (full body) | Function / block |
| var x | undefined | Function |
| let x / const x | ReferenceError (TDZ) | Block |
| class Name {} | ReferenceError (TDZ) | Block |
| var f = function () {} | TypeError: f is not a function | Function |
Function expressions and arrow functions are values assigned to a variable. Only the variable is hoisted; the function value arrives when the assignment line runs. With var you end up calling undefined and get a TypeError; with const the TDZ gives you a ReferenceError. Rather than relying on hoisting, the rule "declare before you use" keeps code readable and bug-free.
- Register every declaration in scope
- function = full body, var = undefined
- let/const/class wait in the TDZ
- Run line by line, assigning values
Nothing is moved; the names are simply known in advance.
General pattern
useDeclared(); // OK: declaration is fully hoisted
function useDeclared() { /* ... */ }
console.log(oldVar); // undefined
var oldVar = value;
console.log(modern); // ReferenceError: TDZ
let modern = value;
useExpression(); // TypeError (var) or ReferenceError (const)
var useExpression = function () { /* ... */ };Four kinds of declaration, used before their lines, give four different results. Only the function declaration works; the rest give undefined or an error.
Example: using five kinds of declaration too early
This example uses each kind of declaration before its line and, when an error occurs, prints the real error name and message from the catch block. That way you see exactly what the engine reports.
// 1. var: the binding exists from the start, value is undefined
console.log(x); // undefined (no error)
var x = 5;
console.log(x); // 5
// 2. let/const: the binding exists but is in the temporal dead zone
try {
console.log(y);
let y = 10;
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
// 3. Function declaration: usable before its line
sayHello();
function sayHello() {
console.log("Hello from hoisted function!");
}
// 4. Function expression stored in var: the variable is undefined
try {
sayBye();
var sayBye = function () {
console.log("Bye!");
};
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}
// 5. Arrow function stored in const: temporal dead zone
try {
sayLater();
const sayLater = () => console.log("Later!");
} catch (e) {
console.log(`${e.name}: ${e.message}`);
}Code breakdown
- Lines 2-3
console.log(x); // undefined (no error)var x was created as undefined during the creation phase, so this prints undefined instead of failing. The = 5 assignment only happens when line 3 runs.
- Lines 8-9
console.log(y);y is declared with let in this block, so its binding exists from the start of the block but sits in the TDZ. The result is the ReferenceError "Cannot access 'y' before initialization", printed here from the real e.message rather than a hand-written string.
- Lines 15-16
function sayHello() {A function declaration is hoisted with its whole body, so the call on line 15 works. This is why helper functions can live at the bottom of a file.
- Lines 22-23
var sayBye = function () {Only var sayBye is hoisted, holding undefined. Calling undefined like a function gives the TypeError "sayBye is not a function".
- Lines 32-33
const sayLater = () => console.log("Later!");The arrow function is stored in a const, so sayLater is in the TDZ. Compare with line 22: the error here is a ReferenceError, not a TypeError.
undefined
5
ReferenceError: Cannot access 'y' before initialization
Hello from hoisted function!
TypeError: sayBye is not a function
ReferenceError: Cannot access 'sayLater' before initializationThe TDZ and shadowing: when the outer variable disappears
One of hoisting's most surprising effects: a level variable exists outside a function, but if the function declares its own let level further down, the top of the function no longer reads the outer one. The inner binding exists from the start of the function and shadows the outer level, so you get a TDZ ReferenceError. Even typeof throws inside the TDZ; it only returns "undefined" for a name that was never declared at all.
let level = "outer";
function show() {
try {
console.log(level);
} catch (e) {
console.log(`${e.name}: the inner level is still in the TDZ`);
}
let level = "inner";
console.log(level);
}
show();
console.log(typeof neverDeclared); // "undefined"
try {
console.log(typeof later);
let later = 1;
} catch (e) {
console.log(`typeof inside the TDZ -> ${e.name}`);
}What happens when a function runs
Every call to a function repeats the creation phase and the execution phase. The diagram below shows what is prepared when checkout() is called. During the execution phase, bindings leave the TDZ one by one as their lines run.
Creation phase vs execution phase for checkout()
------------------------------------------------
function checkout() { CREATION PHASE (before line 1 runs)
var total = 0; total -> undefined
const tax = 0.05; tax -> <uninitialised: TDZ>
function addTax(n) { ... } addTax -> function (full body)
... EXECUTION PHASE
} line 1: total = 0
line 2: tax = 0.05 (TDZ ends here)In real projects
Where this shows up in real projects
One deliberate use of hoisting in real projects is putting a file's main logic at the top and its detailed helper function declarations at the bottom. Readers see "what this file does" first and can dig into details later. That layout only works because function declarations are fully hoisted.
Everywhere else, most teams guard against hoisting rather than rely on it. ESLint's no-var and no-use-before-define rules flag var and early use. When legacy code is migrated from var to let/const, new TDZ ReferenceErrors often appear, and they usually expose real bugs that had been running silently with undefined. Predicting hoisting output is also a very common interview question, so it pays to be able to explain each case out loud.
Common mistakes
Common mistakes
1. Thinking hoisting moves the value too
When var x = 5; is hoisted, the x = 5 assignment stays where it is, so an early read gives undefined, not 5. Remember: the declaration is registered early, but the initializer (= value) only runs when its line is reached.
2. Calling a function expression early like a declaration
Refactoring function helper() {} into const helper = () => {} turns every helper() call above it into a ReferenceError. When you switch to an arrow function, move its declaration above the first use.
3. Missing that an inner let hides the outer variable
Declaring a let with the same name as an outer variable near the bottom of a function makes every earlier use of that name in the function a TDZ error. Avoid reusing names across nested scopes.
Best practices
Best practices
- Avoid var: default to const and use let only when you must reassign, so the TDZ catches early use immediately.
- Declare variables near the top of their scope, close to where they are first used.
- If you rely on hoisting on purpose, do it only with function declarations, and keep ESLint's no-use-before-define switched on.
Mini challenge
Mini challenge: a hoisting probe
Write a probe() helper that runs a function and prints either its result or the error name. Use it to test what happens when five kinds of declaration are used before their line. Write down your predictions before running it.
- probe(label, fn) runs fn() inside try/catch and prints "label: result" or "label: ErrorName"
- Probe five cases: var, let, a function declaration, a var function expression, and a class
- In each probe's function body, the declaration must come after the line that uses it
function probe(label, fn) {
// TODO: run fn() inside try/catch
// TODO: print "label: result" on success, "label: ErrorName" on failure
}
// TODO: probe("var", ...) read a var above its declaration
// TODO: probe("let", ...) read a let above its declaration
// TODO: probe("function declaration", ...) call it above its definition
// TODO: probe("var function expression", ...) call it above the assignment
// TODO: probe("class", ...) use new above the classExpected: Compare these with your predictions: var: undefined let: ReferenceError function declaration: 5 var function expression: TypeError class: ReferenceError
Show hint
Each arrow function body is a new scope; in probe("var", () => { const r = v; var v = 1; return r; }); v is hoisted to the top of that arrow function. Get the error name from e.name.
Show solution
function probe(label, fn) {
try {
console.log(`${label}: ${fn()}`);
} catch (e) {
console.log(`${label}: ${e.name}`);
}
}
probe("var", () => {
const read = v;
var v = 1;
return read;
});
probe("let", () => {
const read = l;
let l = 1;
return read;
});
probe("function declaration", () => {
return add(2, 3);
function add(a, b) {
return a + b;
}
});
probe("var function expression", () => {
const result = multiply(2, 3);
var multiply = function (a, b) {
return a * b;
};
return result;
});
probe("class", () => {
const point = new Point();
class Point {}
return point;
});Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Hoisting does not move code; declarations are registered during the creation phase.
- Function declarations are hoisted with their body; var is hoisted as undefined.
- let, const and class stay in the TDZ until their line, and early use throws a ReferenceError.
- Function expressions and arrows behave like their variable, so calling them early fails; declare before use.
MDN — JavaScript Guide — MDN Web Docs