What is Temporal Dead Zone?

Confused or worried about Temporal Dead Zone (TDZ), then you have come to the right place. Let’s understand this in very simple terms.

Layman Term’s

Consider a scenario where there is a room, some people, and a receptionist. As and when people enter that room, the receptionist gives a name tag to each and everyone with different and unique names and these persons communicate with each other with the same name as mentioned in the tag. Now, there are three persons i.e. Person1, Person2, Person3 are going into the room. The receptionist gives Person1 with name tag A and Person2 with name tag B, when Person3 turns came, he/she went to some work and Person3 become nameless in the room. Now some PersonY can communicate with Person1 & Person2 with the name on the tag but cannot communicate with Person3 as there is no name tag, even if he tries to communicate with some random name Person3 won’t reply as that is not his name. The zone/duration from Person3 entered into the room & till he gets a name tag to is called Temporal Dead Zone.

Technical Term’s

Temporal Dead Zone also known as TDZ is used in reference to ‘const’ and ‘let’. Variables declared with these cannot be read/written until they have been fully initialized. Accessing the variable before the initialization results in Reference Error.

Let’s correlate TDZ with previous example:

// {} is a room
{ // TDZ starts from beginning of the scope

  // Receptionist handing name tags
  let Person1 = 'A';
  let Person2 = 'B';

  // PersonY trying to communicate with Person1, Person2

  console.log('PersonY says Hi to ', Person1); // 'PersonY says Hi to A'
  console.log('PersonY says Hi to ', Person2); // 'PersonY says Hi to B'
  console.log('PersonY says Hi to ', Person3); //  Reference Error


  let Person3 = 'C'; // End of TDZ
}

Few more examples:

{
  // This is the temporal dead zone for the foo variable!
  // This is the temporal dead zone for the foo variable!
  console.log(bar); // undefined
  console.log(foo); // ReferenceError
  var bar = 1;
  let foo = 2; // End of TDZ (for foo)
}

The value of bar gets undefined with no error because of hoisting, which we will learn later.

function createTDZ(a=b, b) {
}

createTDZ(undefined, 1);

It throws a reference error because variable a tries to access variable b which is not declared.

Final Example:

let a = f(); // 1
const b = 2;
function f() { return b; } // 2, b is in the TDZ

In the first line, we call function f which returns the value of b, but the value of b is not declared i.e. why it throws reference error.

References :

Advanced JavaScript ES6 - Temporal Dead Zone, Default Parameters And Let vs Var - Deep dive!

What is the Temporal Dead Zone (TDZ) in JavaScript?

Thank you for Reading!