Let and Const: The Temporal Dead Zone (TDZ)
What you'll learn: Why accessing let or const variables before their declaration throws a ReferenceError, unlike var which returns undefined.
The Core Idea
You learned that var is hoisted and initialized to undefined, so you can reference it before its declaration line (though you shouldn't). With let and const, things work differently: they're hoisted too, but they enter a "Temporal Dead Zone" (TDZ) from the start of the block until the line where they're declared.
During the TDZ, the variable exists in the scope but cannot be accessed. Any attempt to use it throws a ReferenceError.
Why This Matters
console.log(myVar); // undefined (hoisted)
var myVar = 5;
console.log(myLet); // ReferenceError: Cannot access 'myLet' before initialization
let myLet = 10;
The TDZ protects you from accidentally using variables before you've properly initialized them. It makes your code safer and easier to debug.
Think of It This Way
Imagine a package delivery: with var, the box arrives immediately but it's empty until the delivery date. With let/const, the box is in transit (TDZ) and trying to open it throws an error—you must wait until it officially arrives (the declaration line).
The TDZ Includes the Entire Block
{
// TDZ starts here for x
console.log(x); // ReferenceError
let x = 20; // TDZ ends
console.log(x); // 20
}
The TDZ exists from the block's opening { until the let or const declaration.
Key Takeaway: The Temporal Dead Zone ensures let and const variables throw a ReferenceError if accessed before declaration, preventing the confusing undefined behavior of var and making bugs easier to catch.