Hoisting and the Temporal Dead Zone
Hoisting is the name for JavaScript's behavior of registering all declarations in a scope before any code in that scope runs. It is often described as "moving declarations to the top", but nothing actually moves: the engine sets up every name first, then runs the code line by line. What a name holds before its declaration line depends on how it was declared: a function declaration is ready to call, a var holds undefined, and let, const and class are in the temporal dead zone and throw if touched.
In One Minute
- Before running a scope, the engine creates all the names declared in it.
- Function declarations are fully hoisted: you can call them before their line.
varis hoisted and set toundefined: early reads giveundefinedsilently.let,constandclassare hoisted but uninitialized: early use throwsReferenceError. That period is the temporal dead zone (TDZ).- Function expressions and arrows follow the rules of the variable that holds them.
Hoisting by Declaration Type
| Declaration | Hoisted? | Value before its line | Early use |
|---|---|---|---|
function f() {} | Yes, with its body | The function | Works |
var x | Yes | undefined | Gives undefined |
let x | Yes | Uninitialized (TDZ) | ReferenceError |
const x | Yes | Uninitialized (TDZ) | ReferenceError |
class C {} | Yes | Uninitialized (TDZ) | ReferenceError |
const f = () => {} | As a const | Uninitialized (TDZ) | ReferenceError |
var f = function () {} | As a var | undefined | TypeError: f is not a function |
Function Declarations
console.log(totalFees([120, 85]));
function totalFees(fees) {
return fees.reduce((sum, f) => sum + f, 0);
}205The whole function, body included, is ready before the first line runs. This is a feature: it lets a file start with the main logic and put helper functions further down.
var: Hoisted as undefined
console.log(balance);
var balance = 120;
console.log(balance);undefined
120Explanation: the engine created balance and set it to undefined before running anything. The first line reads that undefined; the assignment on line 2 happens only when that line runs. The code behaves as if it were written like this:
var balance; // declaration: set up before anything runs
console.log(balance); // undefined
balance = 120; // assignment: stays where it was written
console.log(balance); // 120Only the declaration is hoisted, never the assignment. The silent undefined is why var bugs are hard to find: nothing fails, the value is just wrong.
let, const and the Temporal Dead Zone
let and const are hoisted too, in the sense that the engine knows about them from the start of their block. But they stay uninitialized until their declaration line runs. Any access before that throws:
try {
console.log(fee);
} catch (err) {
console.log(err.name + ": " + err.message);
}
let fee = 120;
console.log(fee);ReferenceError: Cannot access 'fee' before initialization
120The time between entering the block and reaching the declaration is the temporal dead zone. "Temporal" because it is about time (when the code runs), not position:
function showRate() {
return rate;
}
try {
showRate();
} catch (err) {
console.log("Too early:", err.message);
}
const rate = 2;
console.log("After the declaration:", showRate());Too early: Cannot access 'rate' before initialization
After the declaration: 2Explanation: showRate is written above the const, but that's fine. What matters is when it runs. Called before line const rate = 2; executes, it hits the TDZ; called after, it works.
The TDZ Proves Hoisting Happens
If let weren't hoisted at all, an inner block would simply see an outer variable with the same name. It doesn't:
const city = "Dallas";
{
try {
console.log(city);
} catch (err) {
console.log(err.message);
}
const city = "Austin";
}Cannot access 'city' before initializationThe inner const city is already registered for the whole block, so it shadows the outer city from the first line of the block, while still uninitialized.
Function Expressions and Arrows
A function stored in a variable is hoisted the same way as the variable:
try {
viaConst();
} catch (err) {
console.log(err.name + ": " + err.message);
}
try {
viaVar();
} catch (err) {
console.log(err.name + ": " + err.message);
}
const viaConst = () => "const";
var viaVar = function () { return "var"; };ReferenceError: Cannot access 'viaConst' before initialization
TypeError: viaVar is not a functionWith var, the name exists but holds undefined, so calling it gives a TypeError ("not a function"), which misleadingly points at the call rather than the order of the code.
Classes
Classes behave like let: hoisted, but in the TDZ until their declaration runs.
try {
new Account();
} catch (err) {
console.log(err.message);
}
class Account {}
console.log(typeof new Account());Cannot access 'Account' before initialization
objectSo, unlike function declarations, classes must be defined before the code that uses them runs.
In Practice
A Fee Tracker file organized to use hoisting well: the main flow at the top (calling function declarations defined below), configuration with const before anything that runs uses it:
const RATE = 2;
const GRACE_DAYS = 10;
main();
function main() {
const students = [{ name: "Navika", daysLate: 4 }, { name: "Srihitha", daysLate: 18 }];
for (const s of students) console.log(describe(s));
}
function describe(student) {
return `${student.name}: late fee $${lateFee(student.daysLate)}`;
}
function lateFee(days) {
return Math.max(days - GRACE_DAYS, 0) * RATE;
}Navika: late fee $0
Srihitha: late fee $16The constants come first because main() runs right away and its helpers read them: calling main() above the const lines would hit the TDZ.
Common Mistakes
Reading a var before assigning it. You get undefined instead of an error. Use let or const.
Calling an arrow function before its line. ReferenceError. Move the call down or use a function declaration.
Using a class before its declaration. Unlike functions, classes aren't usable early.
Assuming hoisting moves code. Only declarations are registered early; assignments and initializers run where they are written.
Under the Hood
Hoisting falls out of how the specification sets up a scope. When a function is called (or a script, module or block starts), the engine performs declaration instantiation: it scans the code for declarations and creates a binding for each in the new environment record before evaluating any statement.
varbindings are created and initialized toundefinedimmediately.- Function declarations are created and initialized with a function object, which is why they can be called early.
let,constandclassbindings are created but left uninitialized. Reading or writing an uninitialized binding throws aReferenceError. The binding is initialized only when evaluation reaches the declaration.
So "hoisting" is just the gap between when a binding is created and when it is initialized: zero for functions, nearly zero for var (initialized to undefined), and up to the declaration line for let, const and class. Engines implement the TDZ check cheaply, and V8 removes it entirely when it can prove a variable is always initialized before use.
Interview Corner
What is hoisting?
The behavior where declarations are processed before code execution in their scope, so bindings exist from the start of the scope. Function declarations are initialized with their function, var with undefined, and let, const and class remain uninitialized (the temporal dead zone) until their declaration executes. Assignments are not hoisted.
What is the temporal dead zone?
The period between entering a scope and executing a let, const or class declaration, during which the binding exists but is uninitialized. Any access throws a ReferenceError. It is temporal (based on execution time), so a function referencing the variable works if called after the declaration runs.
What does this print?
Show solution
var a = 1;
function test() {
console.log(a);
var a = 2;
return typeof hoisted;
function hoisted() {}
}
console.log(test());undefined
functionInside test, the local var a is hoisted and shadows the outer a, so the first log prints undefined, not 1. hoisted is a function declaration, available even though it appears after the return.
Practice
Challenge: This code throws. Fix it by moving one line, without changing any line's text.
console.log(format(120));
const CURRENCY = "USD";
const format = (amount) => `${amount} ${CURRENCY}`;Show solution
const CURRENCY = "USD";
const format = (amount) => `${amount} ${CURRENCY}`;
console.log(format(120));120 USDKey Takeaways
| Declaration | Before its line |
|---|---|
function f(){} | Callable |
var x | undefined |
let / const / class | ReferenceError (TDZ) |
var f = function(){} | TypeError when called |
Was this tutorial helpful?