Sub topic 10
The Temporal Dead Zone
This chapter assumes you already know how var hoisting works: the creation phase registers a var name and sets it to undefined before any code runs. You should also be comfortable with block scope for let and const, and with running snippets in Node.js or a browser console. Here we look at what happens to let, const, and class names between the start of their scope and the line that declares them.
What the Temporal Dead Zone Is
let, const, and class declarations are hoisted. During the creation phase of a scope, the engine registers every one of these names. Unlike var, it does not give them a value. The binding exists but stays uninitialized until execution reaches the declaration itself.
The temporal dead zone (TDZ) is the stretch of time between entering the scope and evaluating the declaration. If you read or write the binding during that time, you get a ReferenceError.
function demo() {
try {
console.log(y);
} catch (e) {
console.log(e.name); // "ReferenceError"
}
let y = 1;
console.log(y); // 1
}
demo();Two facts about this code are easy to mix up:
- The name
yis known for the whole function body. That is the hoisting part. - The name
ycannot be used untillet y = 1runs. That is the TDZ part.
If let were not hoisted at all, console.log(y) would look outward through the scope chain and find any outer y. It doesn't. The inner declaration has already claimed the name for the whole block.
How It Compares to var and Function Declarations
| Declaration | Hoisted? | Value before the declaration line | Access before the declaration line |
|---|---|---|---|
| `var x` | Yes | `undefined` | Works, returns `undefined` |
| `function f() {}` | Yes | The full function | Works, can be called |
| `let x` | Yes | Uninitialized | `ReferenceError` |
| `const x` | Yes | Uninitialized | `ReferenceError` |
| `class C {}` | Yes | Uninitialized | `ReferenceError` |
A let declaration with no initializer, such as let x;, ends the TDZ and sets x to undefined when that line runs. const must always have an initializer, so const x; is a SyntaxError before the code even starts.
"Temporal" Means Time, Not Position
The zone is defined by when code runs, not by where it sits in the file. A function written above a let declaration can still use that binding safely, as long as the function is called after the declaration has run.
function show() {
return msg;
}
try {
show(); // msg is still in its TDZ
} catch (e) {
console.log(e.name); // "ReferenceError"
}
let msg = "ready";
console.log(show()); // "ready"The body of show is identical both times. The first call happens while msg is uninitialized. The second happens after let msg = "ready" has run. This is why code that defines helper functions at the top of a module and top-level let or const values further down usually works: the helpers are only called later.
typeof Is Not a Safe Probe Here
typeof on a name that was never declared returns "undefined" and never throws. Developers sometimes rely on that as a guard. The guard breaks for names that are in their TDZ:
console.log(typeof notDeclaredAnywhere); // "undefined"
try {
console.log(typeof z);
} catch (e) {
console.log(e.name); // "ReferenceError"
}
const z = 0;The engine treats these two cases differently. An undeclared name has no binding anywhere on the scope chain, so typeof falls back to "undefined". A name in its TDZ does have a binding. The lookup succeeds and finds it uninitialized, so it throws.
Reading the Error Messages
Engines word the two kinds of ReferenceError differently, and the wording tells you which problem you have. The exact text depends on the engine. In V8 (Chrome and Node.js):
| Situation | Typical V8 message |
|---|---|
| Name is in its TDZ | `Cannot access 'y' before initialization` |
| Name is not declared anywhere | `y is not defined` |
Firefox reports the TDZ case as can't access lexical declaration 'y' before initialization. Whatever the engine, "before initialization" means the declaration exists and you reached it too early. "Not defined" means a typo or a missing declaration.
TDZ Traps That Catch Intermediate Developers
Shadowing Inside an Initializer
A common mistake is trying to build a new inner variable from an outer one with the same name:
let value = 1;
{
try {
let value = value + 1; // which value?
console.log(value);
} catch (e) {
console.log(e.name); // "ReferenceError"
}
}
console.log(value); // 1Inside the try block, let value shadows the outer value for the entire block, including its own initializer. When the right-hand side value + 1 is evaluated, the inner binding is still uninitialized. The lookup stops at the inner binding and never reaches the outer 1. The fix is to use a different name, for example let next = value + 1;.
Default Parameters
Function parameters are initialized left to right, and each one is in a TDZ until its turn. A default value can refer to earlier parameters, but not later ones:
function pair(a = b, b = 2) {
return [a, b];
}
console.log(pair(1)); // [1, 2] (a's default is never evaluated)
try {
pair();
} catch (e) {
console.log(e.name); // "ReferenceError"
}
function pairFixed(b = 2, a = b) {
return [a, b];
}
console.log(pairFixed()); // [2, 2]pair(1) works because a receives an argument, so its default expression b never runs. The error only appears for some call patterns, which makes it easy to miss in testing.
Classes Are Not Like Function Declarations
Function declarations are fully hoisted, so it is tempting to assume classes are too. They are not:
try {
new Animal();
} catch (e) {
console.log(e.name); // "ReferenceError"
}
class Animal {
speak() {
return "...";
}
}
console.log(new Animal().speak()); // "..."The same applies to a class that extends another class declared later in the file. class Dog extends Animal {} evaluates Animal when the Dog declaration runs, so Animal must already be initialized by then. Order base classes before subclasses.
switch Cases Share One Block
All case clauses in a switch share a single block. A let declared in one case is visible in every case, but it is only initialized if the case that declares it actually ran:
function label(n) {
switch (n) {
case 0:
let text = "zero";
return text;
case 1:
text = "one"; // same binding, never initialized on this path
return text;
}
}
console.log(label(0)); // "zero"
try {
label(1);
} catch (e) {
console.log(e.name); // "ReferenceError"
}Wrap each case body in its own braces (case 0: { ... }) so each case gets its own block. Linters such as ESLint flag the unwrapped form with the no-case-declarations rule.
Loop Headers
The TDZ also applies in loop headers. In for (let item of item), the item on the right refers to the new loop variable, which is still uninitialized, so it throws. Name the collection and the element differently, for example for (let item of items).
Why JavaScript Has a TDZ
The TDZ was introduced with let and const in ES2015 for two reasons.
consthas to mean something. If aconstbinding started out asundefinedthe wayvardoes, code could see it holding two different values:undefinedfirst, then its real value. The TDZ makes sure aconstis only ever seen with the one value it was given.- Early access is almost always a bug. Reading a
varbefore assignment silently producesundefined, which then spreads through calculations asNaNor failed checks far from the real cause. AReferenceErrorat the exact line is easier to diagnose.
The practical rule follows from this: declare let, const, and class bindings at the top of the scope where they are used, before any code that reads them. If you do that, the TDZ never affects working code. It only shows up when the execution order is wrong.
Exercises
Exercise
What does this code log, and why? let total = 10; function add() { console.log(total); let total = 5; } add();
Show answer
It throws a ReferenceError ("Cannot access 'total' before initialization" in V8) and logs nothing. The let total inside add is hoisted to the top of the function body and shadows the outer total for the whole function. When console.log(total) runs, the inner binding is still in its TDZ, so the lookup stops there and never reaches the outer value 10.
Exercise
A teammate guards a feature with if (typeof config === "undefined") { /* use defaults */ } placed above const config = loadConfig(); in the same scope. Will the guard work? What should they do instead?
Show answer
No. config has a binding in that scope that is still in its TDZ, so typeof config throws a ReferenceError instead of returning "undefined". They should move the check below the declaration and test the value, for example const config = loadConfig() ?? defaults;, or declare let config; first and assign it later.
Exercise
Given function range(end = start + 10, start = 0) { return [start, end]; }, which of the calls range(), range(5), and range(undefined, 3) throw, and how would you fix the function?
Show answer
range() and range(undefined, 3) throw a ReferenceError, because in both calls end falls back to its default, which reads start while start is still in its TDZ. range(5) returns [0, 5], because the default for end is never evaluated. To fix it, put start first: function range(start = 0, end = start + 10).