Sub topic 6
The Temporal Dead Zone
This chapter assumes you can write and call functions, use try...catch, and read a ReferenceError in the console. It also builds on the previous chapter. There you saw that let and const declarations are hoisted, but reading one before its declaration throws instead of returning undefined. This chapter explains why that happens, what exactly counts as "before," and the less obvious places where the error shows up.
What the Temporal Dead Zone Is
When JavaScript enters a scope, it creates a binding for every let, const, and class declared in that scope. A binding is the link between a name and a storage slot. Unlike a var binding, these bindings start out uninitialized. An uninitialized binding has no value at all, not even undefined.
The temporal dead zone (TDZ) is the period between entering the scope and running the declaration statement. During that period, any attempt to read or write the name throws a ReferenceError. Once the declaration runs, the binding is initialized and the TDZ ends.
function readBeforeDeclare() {
try {
console.log(value); // value exists, but is uninitialized
} catch (e) {
console.log(e.name, '-', e.message);
}
let value = 'ready'; // the TDZ ends here
console.log(value); // 'ready'
}
readBeforeDeclare();
// ReferenceError - Cannot access 'value' before initialization
// readyThe exact message depends on the engine. V8 (Chrome, Node.js) says "Cannot access 'value' before initialization", and Firefox says "can't access lexical declaration 'value' before initialization". Both mean the name exists in this scope and has not been initialized yet.
Two different ReferenceErrors
Learn to tell these two messages apart:
| Message (V8) | Meaning | Usual cause |
|---|---|---|
| `x is not defined` | No binding named `x` exists in any enclosing scope | Typo, missing import, or wrong scope |
| `Cannot access 'x' before initialization` | A binding exists but is still in the TDZ | Code runs before the `let`/`const`/`class` line |
The first error says the name doesn't exist. The second says the name exists but your code reached it too early. You fix them in different ways.
"Temporal" Means Time, Not Position
The TDZ depends on when code runs, not on where it sits in the file. Code written above a declaration can still use the variable if it runs after the declaration has run. The usual case is a function that refers to a variable declared later in the outer scope:
function showGreeting() {
return greeting; // refers to the outer let below
}
try {
showGreeting(); // called while greeting is still in the TDZ
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
let greeting = 'hello';
console.log(showGreeting()); // 'hello': same function, called after initializationThe function body is identical in both calls, and the only difference is timing. That is why the TDZ cannot always be caught when the file is parsed. The engine checks for it at runtime, every time the binding is accessed.
Event handlers, callbacks, and functions passed to setTimeout usually run later, so they rarely hit the TDZ. Code that runs right away during setup hits it more often, such as an immediately invoked function or a constructor called at module load.
Writes Are Blocked Too
The TDZ blocks assignment as well as reading. Assigning to a let before its declaration throws a ReferenceError. It does not quietly create the variable early.
function earlyWrite() {
try {
count = 5; // assignment during the TDZ
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
let count = 0;
console.log(count); // 0
}
earlyWrite();Compare this with var. With var, count = 5 before the declaration would assign to the hoisted variable, and the later var count = 0 would overwrite it. That kind of order-dependent behavior is what the TDZ exists to prevent.
A Declaration Without an Initializer
let x; does not leave x uninitialized forever. When the declaration statement runs, the binding is initialized to undefined:
function noInitializer() {
try {
console.log(x);
} catch (e) {
console.log(e.name); // 'ReferenceError': still in the TDZ
}
let x; // TDZ ends; x is initialized to undefined
console.log(x); // undefined
x = 3;
console.log(x); // 3
}
noInitializer();const has no such form, because const y; is a SyntaxError. A const has to get its one and only value at the moment its TDZ ends.
typeof Is No Longer Safe
typeof on a name that was never declared returns 'undefined' and never throws. Older code used this to check whether a global existed. Inside a TDZ, typeof loses that guarantee:
console.log(typeof neverDeclared); // 'undefined': no binding anywhere
function checkLater() {
try {
console.log(typeof later); // binding exists but is uninitialized
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
let later = 1;
}
checkLater();Shadowing and the Self-Reference Trap
An inner declaration hides, or shadows, an outer variable with the same name for the whole inner scope. That scope begins at the opening brace, not at the declaration line. So an inner let or const hides the outer variable even on the lines above it, and those lines land in the TDZ.
const limit = 10;
function raiseLimit() {
try {
const limit = limit + 1; // right-hand side reads the INNER limit
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
}
raiseLimit();
console.log(limit); // 10You might expect limit + 1 to read the outer limit and produce 11. It doesn't, because the inner limit already owns that name for the whole block, and its initializer runs before the binding is initialized. The fix is to use a different name, such as const raised = limit + 1;.
The same trap appears when someone "copies" a variable into a block during a refactor:
let user = 'Ada';
{
try {
let user = user.toUpperCase(); // inner user is in its own TDZ
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
}Default Parameters Have a TDZ
Parameters are initialized left to right. A default value can use parameters to its left, because those are already initialized. It cannot use parameters to its right, because they are still in the TDZ.
function rangeBroken(start = end - 10, end = 20) {
return [start, end];
}
try {
rangeBroken(); // start's default reads end before end is initialized
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
function rangeFixed(end = 20, start = end - 10) {
return [start, end];
}
console.log(rangeFixed()); // [10, 20]
console.log(rangeBroken(0)); // [0, 20]: no default evaluated for start, so no TDZ accessThe last line shows the timing again. The TDZ only matters when the default expression actually runs.
Classes Behave Like let
Function declarations are fully hoisted, so you can call them before the line where they appear. Class declarations are not. Like let, they get a binding when the scope is entered and stay in the TDZ until the declaration runs.
console.log(area(2)); // 4: function declarations are usable early
function area(side) {
return side * side;
}
try {
new Point(1, 2);
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
console.log(new Point(1, 2).x); // 1This often catches people who move a helper class to the bottom of a file, the way they would with a helper function.
| Declaration | Binding created at scope entry | State before the declaration runs | Access before the declaration |
|---|---|---|---|
| `var` | Yes | `undefined` | Returns `undefined` |
| `function` declaration | Yes | The function object | Works normally |
| `let` | Yes | Uninitialized | `ReferenceError` |
| `const` | Yes | Uninitialized | `ReferenceError` |
| `class` | Yes | Uninitialized | `ReferenceError` |
The switch Statement Gotcha
All case clauses in a switch share one block. A let declared under one case therefore belongs to the whole switch. If control jumps straight to a later case, the declaration never ran, and the binding is still in the TDZ.
function label(kind) {
switch (kind) {
case 'a':
let msg = 'Option A';
return msg;
case 'b':
msg = 'Option B'; // same msg binding, but its declaration was skipped
return msg;
}
}
console.log(label('a')); // 'Option A'
try {
label('b');
} catch (e) {
console.log(e.name); // 'ReferenceError'
}To fix it, wrap each case's body in its own braces so each has its own block and its own variable:
function labelFixed(kind) {
switch (kind) {
case 'a': {
const msg = 'Option A';
return msg;
}
case 'b': {
const msg = 'Option B';
return msg;
}
}
}
console.log(labelFixed('b')); // 'Option B'ESLint's no-case-declarations rule flags the unbraced version.
A Binding That Never Leaves the TDZ
If a let or const initializer throws, the declaration never finishes, so the binding is never initialized. Inside a function, the binding disappears when the function exits, so this rarely matters. At the top level of a classic script it can matter. All classic scripts on a page share one global scope for let and const. A failed top-level initializer leaves that name stuck in the TDZ for every script loaded afterwards, and those scripts get a ReferenceError when they use it.
function loadConfig() {
throw new Error('config missing');
}
try {
// Simulate a failing initializer inside a block so we can observe it
eval(`
let settings = loadConfig();
`);
} catch (e) {
console.log(e.message); // 'config missing'
}You will mostly see this in a browser console or the Node.js REPL. Suppose you type let a = undefinedFunction(); and it throws. After that, reading a in the same session throws "Cannot access 'a' before initialization". If you hit that in a REPL, start a new session or pick a new name.
Why JavaScript Has a TDZ
You may wonder why let doesn't just behave like var and return undefined. The TDZ has two reasons:
constmust have exactly one value. If aconstcould be read asundefinedbefore its declaration and as its real value afterward, code could see two different values for one constant. The TDZ guarantees that every read of aconstreturns the same value.- It turns silent bugs into loud ones. With
var, reading a variable too early givesundefined, which can travel far through your program before something breaks. AReferenceErrorpoints at the exact line that ran too early.
Common Errors Checklist
- An inner variable has the same name as an outer one and reads it in its own initializer (
const x = x + 1). - A default parameter refers to a parameter to its right.
- A class is used before its declaration, often by code at the top level of a module.
letorconstsits directly under acasewith no braces around it.typeofis used to "safely" check a name that is declared later in the same scope.- A function that reads an outer
letis called during setup, before thatletline has run.
Exercises
Exercise
What does this program print, and why? let total = 100; function apply() { console.log(total); let total = 0; } apply();
Show answer
It throws a ReferenceError ("Cannot access 'total' before initialization") and prints nothing. The let total inside apply shadows the outer total for the whole function body. So the console.log reads the inner binding, which is still in its temporal dead zone. It does not fall back to the outer value of 100.
Exercise
The call makeUser() throws a ReferenceError. Fix the function without changing what it returns when called with no arguments. function makeUser(name = defaultName, defaultName = 'guest') { return name; }
Show answer
Swap the parameter order so the default for name refers to a parameter that is already initialized: function makeUser(defaultName = 'guest', name = defaultName) { return name; }. Note that this changes the positional signature. If callers pass name as the first argument, keep the original order and move the default into the body instead: function makeUser(name, defaultName = 'guest') { return name === undefined ? defaultName : name; }.
Exercise
Will the last line log 'ready' or throw? Explain using the word "temporal." const getStatus = () => status; let status = 'ready'; console.log(getStatus());
Show answer
It logs 'ready'. The arrow function refers to status before the let line in the source, but the TDZ is about when code runs, not where it is written. By the time getStatus() runs, let status = 'ready' has already run and initialized the binding, so the read succeeds.