What is Temporal Dead Zone (TDZ) in JavaScript?

JavaScriptDEShawTekion

Temporal Dead Zone (TDZ)

In ES6, accessing a let or const variable before its declaration (within its scope) causes a ReferenceError. The time span when that happens, between the creation of a variable’s binding and its declaration, is called the temporal dead zone.

The reaon TDZ exists is not because of let, it is because of const. Think about const being attached inside of a block scope.

Imagine if const initialized itself to undefined. And then on line 1 of the block you did console.log of that variable and you saw it undefined, and then later you saw it with value 42. Technically, that const would have two different values at two different times, which academically violates the concept of a const. So they said we have to prevent you from accessing a variable earlier in the scope then when it's been assigned one and only one value, so that you can't observe it in that intermediate state.

// Without TDZ (hypothetical scenario):
console.log(number); // Would be undefined
const number = 42; // Now it's 42
// This would violate const's single-value principle!

// With TDZ (actual behavior):
console.log(number); // ReferenceError
const number = 42; // As expected

The key point: TDZ exists to maintain the integrity of const declarations and to help catch potential bugs early in development.

You can read more about TDZ in the MDN documentation.

00:00

Table of Contents