What is the temporal dead zone (TDZ)?
The temporal dead zone is the period between the start of a scope and the line where a let, const or class is declared; the binding already exists (it is hoisted) but is uninitialised, so any access during that period throws a ReferenceError.
Why it exists
With var, reading a variable before its declaration silently gives undefined, which hides bugs. The TDZ turns these mistakes into immediate, clear errors. It also makes const meaningful: a constant can never be observed in an "unassigned" state.
"Temporal", not positional
The TDZ is about when code runs, not where it is written. A function can reference a let declared below it, as long as the function is called after the declaration has executed.
Places the TDZ shows up
- Using a variable before its
let/constline in the same scope. - Shadowing: an inner
let xputsxin the TDZ for the whole inner block, so even reading the outerxthere throws. - Default parameters referring to later parameters:
function f(a = b, b = 1). - Classes: using a class before its declaration, and
extendsexpressions that reference the class being defined. typeofis not safe here:typeof xthrows in the TDZ (unlike for undeclared variables).- Modules with circular imports: importing a binding that has not been initialised yet throws.
Practical advice
Declare variables at the top of their scope or right before first use, avoid relying on hoisting, and lint for no-use-before-define.
Code example
1// 1. Basic TDZ2try {3 console.log(total);4} catch (e) {5 console.log(e.name); // ReferenceError6}7let total = 10;89// 2. Temporal, not positional: the function runs after the declaration10function showLimit() {11 return limit;12}13const limit = 5;14console.log(showLimit()); // 51516// 3. Shadowing puts the inner name in the TDZ for the whole block17const theme = "dark";18{19 try {20 console.log(theme); // refers to the INNER theme, which is still in the TDZ21 } catch (e) {22 console.log("shadowed:", e.name); // shadowed: ReferenceError23 }24 const theme = "light";25}2627// 4. typeof is not safe in the TDZ (but is for undeclared names)28console.log(typeof neverDeclared); // "undefined"29try {30 typeof later;31} catch (e) {32 console.log("typeof:", e.name); // typeof: ReferenceError33}34let later = 1;3536// 5. Default parameters are evaluated left to right37function range(start = end - 5, end = 10) {38 return [start, end];39}40try {41 range(undefined, 10); // still throws: `end` is uninitialised while `start`'s default runs42} catch (e) {43 console.log("default param:", e.name); // default param: ReferenceError44}45const range2 = (end = 10, start = end - 5) => [start, end]; // refer only to EARLIER params46console.log(range2()); // [5, 10]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.