JavaScript Temporal Dead Zone (TDZ) Tutorial

In this section, we will learn what the Temporal Dead Zone or TDZ is and how it works in JavaScript.

Note: In this section, we’re assuming you’re already familiar with the hoisting in the JavaScript.

JavaScript Hoisting and Temporal Dead Zone: let and const Keywords

When the compiler registers each variable in its scope, if that variable is created via the `var` keyword, it will also assign the default value `undefined` to it.

For this reason, we can call a `var` type variable before the statement in which the actual declaration happened. In a situation like this, we get the value `undefined`.

But if that identifier is created via the `let` or `const` keyword, it won’t have the value `undefined` as its initial value. For this reason, we can’t call a `let` or `const` identifier before the statement where the identifier is declared. If we do so, we will get the `uninitialized error`.

Again, this is because the `let` and `const` identifiers don’t get the default value `undefined` when they are registered in their scope.

So the area from the opening brace `{` of the scope of the `let` or `const` identifier to the line where the actual initialization happens is called `Temporal Dead Zone (AKA TDZ)`. This means we cannot call the identifier in this zone because the variable is not declared and doesn’t have any initial value then. If we call such variables in this zone, we will get an error instead.

Example: Temporal Dead Zone error in JavaScript

{
 //Temporal Dead Zone for the firstName variable
 //Temporal Dead Zone the firstName variable
 //Temporal Dead Zone the firstName variable
 //Temporal Dead Zone the firstName variable
 //Temporal Dead Zone the firstName variable
 let fisrtName = "John";
 console.log(fisrtName);
} 

Output:

John

Here because the call to the `console.log(firstName);` statement occurred after the declaration of the `firstName` variable; it’s out of TDZ area and so we won’t get the error.

But if we change the location of the `console.log(firstName);` statement and put it on top of the `firstName` variable, we will get the error.

This is because we’re trying to access the variable before its actual declaration.


Example: throwing temporal dead zone error in JavaScript

{
 //Temporal Dead Zone the firstName variable
 //Temporal Dead Zone the firstName variable
 //Temporal Dead Zone the firstName variable
 //Temporal Dead Zone the firstName variable
 console.log(fisrtName);
 //Temporal Dead Zone the firstName variable
 let fisrtName = "John";
 
} 

Output:

ReferenceError: Cannot access 'fisrtName' before initialization

Leave a Reply