Temporal Dead Zone
Overview
The Temporal Dead Zone (TDZ) is the period of time between when a let or const variable is hoisted into memory and when it is actually initialized with a value.
During this 'dead zone', trying to access the variable results in a crash. This was added to ES6 to stop developers from writing sloppy code.
Syntax
The variable name is technically known to JS at line 1, but it's locked in the TDZ until line 5 executes.
// --- START OF TEMPORAL DEAD ZONE FOR 'name' ---
console.log("App started");
console.log(name); // ReferenceError: Cannot access 'name' before initialization
// --- END OF TEMPORAL DEAD ZONE ---
const name = "Kartik"; // Initialization happens hereCommon Pitfalls
- Getting confused when debugging because you assume
letandconstaren't hoisted at all. They are hoisted, but the TDZ prevents you from using them, unlikevarwhich silently returnsundefined.
Interview Questions
It is a behavior in JS where 'let' and 'const' variables exist in scope but cannot be accessed until their line of declaration is executed. Any attempt to access them in the TDZ throws a ReferenceError.
Real-World Example
The TDZ protects you in complex React applications. If you accidentally try to use a piece of state or a prop configuration before you've defined it, the app crashes instantly with a clear error, rather than failing silently later on.
function renderProfile() {
// TDZ prevents this bug
console.log(config); // Error!
const config = { theme: "dark" };
}Check Your Knowledge
Test your understanding of Temporal Dead Zone with these quick questions.