/
Write
Start a team blog
NEW ✨
Start a team blog, invite your team, and start publishing.

☠️Temporal Dead Zone

Anshika Agarwal's photo
Anshika Agarwal
·Jan 16, 2022·

2 min read

Let's have a look on what exactly a Temporal or as I like to call it Terrifying Dead Zone is.

Temporal Dead Zone is the time period between which a variable is declared , to the point where it is initialized. To understand it better, we first need to dive a bit into a concept called hoisting

HOISTING

In JavaScript all the variables, let it be initialized with let , var or const are hoisted. Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. So every variable declared anywhere in the code is moved to the top of the scope by the interpreter before execution of actual code even begins. now, hoisting is different for var and let, const.

In var, the variable gets hoisted in the global object and no TDZ is faced but in let and const the variable is hoisted in script scope and given a memory location that cannot be accessed before initializing the variable. this causes TDZ in let and const.

example:

console.log(a);  // here 'undefined' will be consoled as no TDZ occurs in var
var a=3;
console.log(a); // here TDZ occurs and Reference error is thrown
let a=3; // now a is initialized
console.log(a); // No TDZ .

Since in the second example we declared let after the calling so TDZ occurred. A reference error is thrown for the same as we are using the variable before it is initialized!

😤How to avoid TDZ

Temporal Dead Zone should be avoided as it can very well mess with a developer. Best way to avoid TDZ is:

Always declare all your variables at the start of your code. This way you can avoid TDZ as there is no space for it to occur because everything is declared before hand.

Hope I was able to simplify TDZ a bit for you! ❣️