Hoisting and the Temporal Dead Zone

Updated · 8 min read
mediumES2026javascripthoistingtdzscopeinterview

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.
  • var is hoisted and set to undefined: early reads give undefined silently.
  • let, const and class are hoisted but uninitialized: early use throws ReferenceError. 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

DeclarationHoisted?Value before its lineEarly use
function f() {}Yes, with its bodyThe functionWorks
var xYesundefinedGives undefined
let xYesUninitialized (TDZ)ReferenceError
const xYesUninitialized (TDZ)ReferenceError
class C {}YesUninitialized (TDZ)ReferenceError
const f = () => {}As a constUninitialized (TDZ)ReferenceError
var f = function () {}As a varundefinedTypeError: f is not a function

Function Declarations

functions.js▶ Try it
console.log(totalFees([120, 85]));
 
function totalFees(fees) {
  return fees.reduce((sum, f) => sum + f, 0);
}
Output
205

The 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

var.js▶ Try it
console.log(balance);
var balance = 120;
console.log(balance);
Output
undefined
120

Explanation: 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-equivalent.js
var balance;          // declaration: set up before anything runs
console.log(balance); // undefined
balance = 120;        // assignment: stays where it was written
console.log(balance); // 120

Only 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:

tdz.js▶ Try it
try {
  console.log(fee);
} catch (err) {
  console.log(err.name + ": " + err.message);
}
let fee = 120;
console.log(fee);
Output
ReferenceError: Cannot access 'fee' before initialization
120

The 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:

tdz-time.js▶ Try it
function showRate() {
  return rate;
}
 
try {
  showRate();
} catch (err) {
  console.log("Too early:", err.message);
}
 
const rate = 2;
console.log("After the declaration:", showRate());
Output
Too early: Cannot access 'rate' before initialization
After the declaration: 2

Explanation: 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:

tdz-shadow.js▶ Try it
const city = "Dallas";
{
  try {
    console.log(city);
  } catch (err) {
    console.log(err.message);
  }
  const city = "Austin";
}
Output
Cannot access 'city' before initialization

The 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:

expressions.js▶ Try it
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"; };
Output
ReferenceError: Cannot access 'viaConst' before initialization
TypeError: viaVar is not a function

With 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.

class.js▶ Try it
try {
  new Account();
} catch (err) {
  console.log(err.message);
}
 
class Account {}
console.log(typeof new Account());
Output
Cannot access 'Account' before initialization
object

So, 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:

organized.js▶ Try 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;
}
Output
Navika: late fee $0
Srihitha: late fee $16

The 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.

  • var bindings are created and initialized to undefined immediately.
  • Function declarations are created and initialized with a function object, which is why they can be called early.
  • let, const and class bindings are created but left uninitialized. Reading or writing an uninitialized binding throws a ReferenceError. 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
puzzle.js▶ Try it
var a = 1;
function test() {
  console.log(a);
  var a = 2;
  return typeof hoisted;
  function hoisted() {}
}
console.log(test());
Output
undefined
function

Inside 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.

broken.js
console.log(format(120));
const CURRENCY = "USD";
const format = (amount) => `${amount} ${CURRENCY}`;
Show solution
fixed.js▶ Try it
const CURRENCY = "USD";
const format = (amount) => `${amount} ${CURRENCY}`;
console.log(format(120));
Output
120 USD

Quick check: Hoisting

3 questions
1What does console.log(x); var x = 5; print?
2What happens with console.log(y); let y = 5;?
3Which can be called before its line in the code?

Key Takeaways

DeclarationBefore its line
function f(){}Callable
var xundefined
let / const / classReferenceError (TDZ)
var f = function(){}TypeError when called

Was this tutorial helpful?

Lesson 43 of 139