Temporal Dead Zone in ES6

Temporal Dead Zone in ES6

After a very long time, Welcome to the third blog of one of the JS Concept which is TDZ(Temporal Dead Zone)

For many of you like me, seems that only var declarations are hoisted and not let & const.

not-me.gif

It may happen because you try to access variables of var before its declarations, and it will give you undefined and not an error.

But when you access let & const variables before its declarations may give you errors like "Cannot access 'var_name' before initialization".

But we all are wrong, all the variable declarations are hoisted in JS.

shock-disbelief.gif

☠️ Temporal Dead Zone:

A temporal dead zone is a time period that starts when variable declarations are hoisted and finishes when those variables are initialized.

let's take an example:

console.log(name);
let name = 'Gopal';
var age=20;

image.png

As you can see above (chrome web dev tool==>sources) tab both variables name and age have assigned the value undefined before executing a single LOC(Line of code).

So now it's clear that all variable declarations are hoisted in JS.

But as you can see that name is in the Script Scope, and age is in the Global scope. And We are in the Global Scope. That's why js Engine can't find the name in Global scope and give an error like below.

image.png

So the time before executing the first line which is consoling name into the console till the time when name assigned a value is Temporal dead Zone for variable name.

According to that, all the LOC(Line of code) which is above the initialization of let & const variables are in the TDZ time period.

Conclusion:

Let & const declarations are also hoisted just like var but in the different scope of the browser which is Script scope. 2. The time period between hoisting and initialization of let & const variables is TDZ.

Resources:

▶️ youtube.com/watch?v=BNC6slYCj50&t=455s