DEV Community

Dev Cookies
Dev Cookies

Posted on

🧠 What is the Temporal Dead Zone?

The Temporal Dead Zone (TDZ) is the time between:

  1. When a let or const variable is hoisted, and
  2. 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;
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Here, you're accessing it after the TDZ is over β€” totally valid.


β›” With var (No TDZ):

console.log(y); // βœ… undefined
var y = 20;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

🀯 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)