The Temporal Dead Zone (TDZ) is a specific behavior in JavaScript that occurs when declaring variables using let and const. It is a source of bugs for developers who assume variable hoisting behaves identically for all keywords.
What is the Temporal Dead Zone?
The TDZ is the period of time from the start of a block's execution until the variable's declaration is executed. During this zone, accessing the variable throws a ReferenceError.
{
// Start of TDZ for variable 'a'
console.log(b); // undefined (var is hoisted and initialized)
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 10; // End of TDZ for variable 'a'
var b = 20;
}
Why does the TDZ exist?
The TDZ was introduced in ES6 for two main reasons:
- Catch Bugs Early: Accessing variables before declaration is usually a programming error. TDZ flags this immediately instead of allowing silent failures with
undefined. - Const Safety: A
constvariable cannot be reassigned. If a hoisted const defaulted to undefined first, it would violate the specification when initialized to its actual value.