What is Temporal Dead Zone in Javascript?

What is Temporal Dead Zone in Javascript?

Introduction

In ES5 there was only one type of variable called var but ES6 introduced 2 more types of variables const and let. So now there are 3 types of variables in Javascript, They are

  1. var
  2. const
  3. let

In these var is function scope variable and const and let are block scoped variables.

What is function scope variable?

If the variable is declared in any block i.e inside {} can be accessed from anywhere within the function, Then this kind of variable is called as function scope variable.

What is block scoped variable?

If the variable declared inside a block i.e inside {} cannot be accessed outside the block, Then this kind of variable is called as block scoped variable.

Temporal deadzone arises because of these block scoped variables.

What is Temporal Dead Zone?

Let's discuss with example code.

function sampleFunc(){
console.log(tempDead);
//
//This is the Temporal Dead Zone, Where it gives Reference Error if we try to access tempDead
//
let tempDead="Hello World";//Here the Temporal Dead Zone ends
}
sampleFunc();
function sampleFunc(){
console.log(tempDead);
//
//This is the Temporal Dead Zone, Where it gives Reference Error if we try to access tempDead
//
const tempDead="Hello World";//Here the Temporal Dead Zone ends
}
sampleFunc();

In the above code snippets we can see that we are trying to access tempDead variable before initialization, So when we try to execute these code we get Reference Error. This is the exact condition where Temporal Dead Zone occurs. The zone between accessing tempDead and intializing tempDead is called as Temporal Dead Zone. Reason behind this is Hoisting

What is Hoisting?

When we declare variable with type var it will be hoisted, that means it will be treated as it is declared at the begining of the function and initialized with undefined as default value but this is not true incase of let and const . let and const will be hoisted but there will not be any default value assigned to those variables, So if we try to access those variables with type let and const before initialization then exception will occur.

function sampleFunc(){
console.log(temp1);//Reference Error
console.log(temp2);//Reference Error
console.log(temp3);//undefined
const temp1="Hello";//Temporal Dead Zone of temp1 ends here
let temp2="World";//Temporal Dead Zone of temp2 ends here
var temp3="Hoisted";
}
sampleFunc();

How we can avoid Temporal Dead Zone?

To avoid this condition try to initialize let and const type of variables at the top of the scope or do not access that kind of variables before initialization.

Thank you