The Temporal Dead Zone (TDZ) is the time between:
- When a
let
orconst
variable is hoisted, and - When it is actually declared/initialized in code.
During this time, the variable exists in memory (because of hoisting), but you can’t access it — doing so throws a ReferenceError
.
📦 Example:
console.log(x); // ❌ ReferenceError: Cannot access 'x' before initialization
let x = 10;
Even though x
is hoisted, it lives in the TDZ from the start of the block until the line let x = 10
.
✅ Good Example (Outside TDZ):
let x = 10;
console.log(x); // ✅ 10
Here, you're accessing it after the TDZ is over — totally valid.
⛔ With var
(No TDZ):
console.log(y); // ✅ undefined
var y = 20;
var
is hoisted and initialized with undefined
, so there's no TDZ. But this can cause bugs, which is why let
and const
were introduced.
🧪 With const
console.log(z); // ❌ ReferenceError
const z = 30;
const
also has a TDZ — and must be initialized at the time of declaration.
🔁 TDZ in a block scope:
{
// TDZ starts
// console.log(a); // ❌ ReferenceError
let a = 5; // TDZ ends
}
🤯 Why Does TDZ Exist?
The TDZ helps prevent bugs by:
- Making variables accessible only after explicit declaration
- Avoiding accidental usage of undefined values
- Encouraging cleaner, more predictable code