Back to Blog Listing

Understanding the Temporal Dead Zone in JS

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:

  1. Catch Bugs Early: Accessing variables before declaration is usually a programming error. TDZ flags this immediately instead of allowing silent failures with undefined.
  2. Const Safety: A const variable cannot be reassigned. If a hoisted const defaulted to undefined first, it would violate the specification when initialized to its actual value.
💻

Try this code in our online compiler!

Don't just read about it. Write, run, and experiment with these JavaScript concepts instantly on our online workspace with autocomplete suggestions.

Share this tutorial:

CodeCompile