DEV Community

Cover image for Temporal dead zone(TDZ)
Ayushi Verma
Ayushi Verma

Posted on

Temporal dead zone(TDZ)

Let's discuss the temporal dead zone in depth!

We Know Let and Const declarations are known to be hoisted.

And, if we talk about hoisting, it's the default behavior of moving all declarations to the top of the scope before code execution, which means we can access variables before they're initialized because in js memory is allocated to each variable even before a single line of code is executed.

Let take an example and try to understand this
Image description
here you can see the varVariable is called before it is being initialized and we did not even get the error, this is because the var is Global scope, varVariable got some memory in the Global scope but the value is not initialized hence giving undefined.

Image description
But wait ! Why are we getting an error here? If you say that I told you that memory is allocated to every variable even before a single line of code is executed, but we still get a reference error. Then hold on, memory is allocated to letVariable, but in a different memory space, which is not global as let being block scope, and we are unable to inspect these let and const before assigning them a value.

Image description
Here's where the Temporal Dead Zone comes in. We're getting the value of letVariable now, and we can see what TDZ is- It is the time between since when the let/const variable was hoisted and till it is initialized some value.

In other words,

The time window in which a variable exists but is still uninitialized and thus cannot be accessed in any way is known as the TDZ. That initialization can only be achieved by implementing the instructions left by the Compiler at the time of the original declaration. The TDZ is now complete, and the variable can be used for the remainder of the scope.

A var also has a TDZ, but it's zero in length and therefore invisible to our programs, Only let and const have a TDZ that can be observed.

And Why TDZ happen?

Let/const declarations are hoisted too but like var they are not auto-initialized until they are initialized in the code sequence, hence resulting in TDZ.

Hope you like it, comment the feedbacks:)
Happy Coding

Top comments (0)