← JavaScript

Intermediate · 3 of 17 · 12 min read

The Temporal Dead Zone

The window where a let or const exists but cannot be touched, why typeof throws in it, and the three snippets that test it.

  • Temporal Dead Zone

A let or const binding is created when the scope is entered, but it has no value — not even undefined — until its declaration line executes. The Temporal Dead Zone is that gap. Reading the name inside it throws a ReferenceError.

The basic shape

{
  // console.log(foo); // ReferenceError: Cannot access 'foo' before initialization
  let foo = 42;
  console.log(foo);    // 42 — the TDZ ended here
}

Compare the three cases side by side, because the error messages differ and each one tells you something:

console.log(typeof nope);  // "undefined" — never declared anywhere
console.log(varName);      // undefined   — declared and initialised by hoisting
// console.log(letName);   // ReferenceError: Cannot access 'letName' before initialization

var varName = 1;
let letName = 2;
State typeof Reading it
Never declared "undefined" ReferenceError: x is not defined
var, before its line "undefined" undefined
let / const, in the TDZ throws ReferenceError: Cannot access 'x' before initialization
let / const, after its line its type its value

The two ReferenceError messages are different on purpose. “is not defined” means no such binding; “Cannot access … before initialization” means the binding is right there and is not ready.

typeof throwing is the surprising part

typeof is otherwise the safe way to ask about a name you are not sure exists:

if (typeof maybeGlobal === 'undefined') {
  console.log('not present'); // the classic feature-detection guard
}

That guard stops working for a let in the same scope:

// if (typeof config === 'undefined') { /* ReferenceError */ }
let config = { debug: true };

So the old typeof check is only a safe guard for names that might not be declared at all — globals, in practice. For a local binding, the declaration is right there in the file; just read it.

Shadowing makes it bite

The TDZ is why a block cannot read the outer variable it is about to shadow:

let value = 10;
{
  // console.log(value); // ReferenceError — the inner `value` already shadows it
  let value = 20;
  console.log(value);    // 20
}
console.log(value);      // 10

This is the single most practically confusing TDZ case, because the line looks like it should read the outer 10. The inner binding exists from the opening brace, so the outer one is unreachable for the whole block.

With var there is no shadow and no error, which is exactly the sloppiness let set out to fix:

var v = 10;
{
  console.log(v); // 10 — same variable
  var v = 20;
}
console.log(v);   // 20 — the block changed the outer value

Default parameters

Parameters are initialised left to right, in their own scope, and each one is in the TDZ until its turn:

function broken(a = b, b = 2) {
  console.log(a, b);
}
// broken(); // ReferenceError: Cannot access 'b' before initialization

function fine(a = 1, b = a + 1) {
  console.log(a, b);
}
fine();      // 1 2
fine(5);     // 5 6
fine(5, 50); // 5 50

A later parameter can depend on an earlier one. The reverse cannot work, and the error is a TDZ error rather than undefined, which makes it findable.

A parameter default also cannot see a let in the function body, because the body’s scope is created after the parameters are bound:

let limit = 10;

function f(max = limit) {
  let limit = 99; // a separate binding, in the body scope
  return max;
}
console.log(f()); // 10 — the default read the outer `limit`

The classic loop difference

The TDZ is also what makes a per-iteration binding possible, which is the real answer to the “closures in a loop” question:

const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
console.log(withVar.map((f) => f())); // [3, 3, 3] — one shared `i`

const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withLet.map((f) => f())); // [0, 1, 2] — a fresh `j` per iteration

Each iteration gets its own j, created fresh — and therefore its own TDZ — which is why the closures captured three different variables instead of one.

Where it also applies

class declarations and const in a switch behave the same way:

// new Thing(); // ReferenceError: Cannot access 'Thing' before initialization
class Thing {}
new Thing();    // fine

switch (1) {
  case 1:
    // console.log(label); // ReferenceError — one block for the whole switch
    const label = 'one';
    console.log(label);    // "one"
    break;
}

A switch body is a single block shared by every case, which is why a const in one case is visible — and in the TDZ — in the cases above it. Wrapping a case in braces gives it its own scope.

Functions defined before, called after

The detail that makes “temporal” the right word:

function read() {
  return secret; // not evaluated yet
}

// read(); // ReferenceError if called here
const secret = 'ready';
console.log(read()); // "ready" — the TDZ had ended by the time it ran

Nothing is wrong with referencing a const from a function written above it. Only executing that reference too early is a problem — the same reason module-level circular imports fail at runtime rather than at parse time.

Common mistakes

Reading the outer variable in a block that shadows it

Mistake. let x = 1; { console.log(x); let x = 2; } Why it fails. The inner x is in scope from the {, so the outer one is shadowed for the whole block and the read lands in the TDZ. What to do instead. Rename one of them. Shadowing with the same name in a nested block is rarely worth the confusion.

Using typeof as a safety net for a local

Mistake. if (typeof value !== 'undefined') for a let declared later in the same scope. Why it fails. typeof throws in the TDZ — it is only safe for names that may not be declared at all. What to do instead. Move the declaration above the use, or initialise it to a default and test the value.

Ordering parameter defaults wrong

Mistake. function f(total = price * qty, price = 1, qty = 2). Why it fails. Defaults evaluate left to right, so price and qty are still in the TDZ when total is computed. What to do instead. Put the dependency first: function f(price = 1, qty = 2, total = price * qty).

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

let and const are hoisted as well — the question is what state they are hoisted into.

What happens when this runs?

Code sample
console.log(y);
let y = 20;

Default parameter values are expressions, and they are evaluated in a particular order.

What happens when this runs?

Code sample
function test(a = b, b = 2) {
  console.log(a, b);
}

test();

typeof someNameThatWasNeverDeclared safely returns "undefined". What does typeof do to a let variable that is still in its TDZ?

Practise Temporal Dead Zone →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.