Photo by Sebastian Herrmann on Unsplash
Temporal Dead Zone in JS
Understanding Temporal Dead Zone (TDZ)..... in JS
Before starting with Temporal Dead Zone it is better that you first understand the concept of Scope and Hoisting in Javascript. If you have then you are good to go else you can refer to my previous blog to get an understanding of the above topic.
Before starting, I would like to tell you that in this blog, I would be referring Temporal Dead Zone as TDZ.
So now let's get started, observe the below code snippet and try to guess what will the output be.
{
// TDZ starts here (at the beginning of this block’s local scope)
// greetMsg’s TDZ continues here
// greetMsg’s TDZ continues here
// greetMsg’s TDZ continues here
// greetMsg’s TDZ continues here
let bestFood = "Vegetable Fried Rice"; // bestFood’s TDZ ends here
console.log(bestFood); // returns "Vegetable Fried Rice" because bestFood’s TDZ does not exist here
// greetMsg's TDZ does not exist here
// greetMsg's TDZ does not exist here
}
A common question that would come to your mind is that if variables are Hoisted in Javascript then why does it throw an error? Yes you are right variables are hoisted in Javascript but if you recall var
is auto-registered+auto-initialized
whereas let and const
are only auto-registered
. So what happens is when variables are hoisted to the time they are initialized they are in a Temporal Dead Zone, trying to access the variables in this region throws a Temporal Dead Zone error or Usage before initialization error.
Temporal Dead Zone can be defined as the period of time from the entering of a scope to where the auto-initialization of the variable occurs is: Temporal Dead Zone (TDZ).
The Temporal Dead Zone TDZ is the time window where a variable exists but is still uninitialized, and therefore cannot be accessed in any way. Only the execution of the instructions left by Compiler at the point of the original declaration can do that initialization. After that moment, the TDZ is done, and the variable is free to be used for the rest of the scope.
Note: A var
also technically has a TDZ, but it's zero in length and thus unobservable to our programs! Only let
and const
have an observable TDZ the reason being var
isauto-registered+auto-initialized
whereas let and const
are only auto-registered
.