Before you think we are going to read about a secret dungeon in Azakaban or something related to zombies, let me clear it out, this scary sounding ‘Temporal Dead Zone’ is just another concept of Javascript.
To understand TDZ, let's start with an exercise.
{
console.log('Name:', name);
const name = 'Tanay';
}
{
console.log('Name:', name);
let name = 'Tanay';
}
{
console.log('Name:', name);
var name = 'Tanay';
}
What would be the output for each of these snippets?
- Error: Variable does not exist?
- Error: Variable is not initialized?
- Anything else?
First two will throw an error
Error: can't access lexical declaration 'name' before initialization
Third one won't throw an error, rather it would log Name:undefined
So why is var
behaving different than let
and const
? To understand this, first let's see what is Hoisting.
Hoisting
Declarations of variables and functions get precedence during the execution of the code. In a way, as the code executes, declarations hop on to the top of the code and are executed before everything else. (This is for understanding and not an accurate depiction, the code doesn't actually move!).
Okay, so why aren't first two code pieces logging undefined
as well?
The catch:
In the case of var
, declaration is hoisted and the variable is initialized with undefined
. But in the case of let
and const
, declaration is hoisted but the variable is not initialized.
Food for thought: Do function declarations also get hoisted? What about function expressions and arrow functions?
Once you know Hoisting, it becomes easy to understand TDZ.
Temporal Dead Zone
Let's see its literal meaning
Temporal - temporary Dead - unavailable Zone - section of code
So the section of a code block in which the variables are inaccessible/not available/dead is called Temporal Dead Zone. In other words, TDZ is an area of the block where we cannot access variables before they are defined.
As we can see, TDZ for let
and const
ends when the variables are initialized, while TDZ for var
ends as soon as it is hoisted.
Does it sound scary anymore, I hope it doesn't!