The Temporal Dead Zone (TDZ) is the time between:
- When a
letorconstvariable 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
Top comments (0)