liveBook · Manning

Temporal dead zone

As explained in Secrets of the JavaScript Ninja, Third Edition

The interval from entering a lexical declaration's scope until its initialization during which accessing the binding throws an error.

Being in scope does not mean a variable is ready to use. The temporal dead zone (TDZ) is the interval before a let, const, or class binding is initialized; accessing it during that interval throws a ReferenceError. section 7.3.2

JavaScript determines which variables belong to a scope before executing its code. A later lexical declaration can therefore put a name in scope even when execution reaches a reference to it first. Avoid the error by ensuring initialization happens before the reference at runtime; textual order alone does not decide whether a reference is safe. section 7.3.2

Do not treat every declaration as if it behaved the same way:

  • An uninitialized let, const, or class binding throws a ReferenceError when accessed. section 7.3.2
  • An uninitialized var binding evaluates to undefined; function declarations are hoisted. section 7.3.2
  • A function body may mention a binding before its declaration, provided the function runs only after that binding is initialized. section 7.3.2
  • typeof can check whether a global exists without a ReferenceError, but using it on a local binding in its TDZ still throws. Move the declaration to the top of the local scope when possible. section 7.4
ReferenceError: Cannot access 'x' before initialization

The runtime error identifies x as not yet initialized. section 7.3.2

const verifyX = () => {
  console.assert(x === 1, "x is 1");
};
const x = 1;
verifyX();

This runs without error: verifyX is called after x has been initialized, even though its body refers to x earlier in the source. section 7.3.2

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains initialization timing, declaration contrasts, delayed function execution, and the local typeof trap.
Examples
Demonstrates an early access error, a safely delayed function call, and a local typeof failure.
What you can do after
Understand why lexical bindings throw before initialization and why runtime execution order matters.
How it connects
Links lexical declarations and scope to hoisting, function declarations, and typeof checks.

Also explained in

Compare how 2 books explain temporal dead zone →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.