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
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.
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! ❣️