What is Temporal Dead Zone in JavaScript ???

What is Temporal Dead Zone in JavaScript ???

Let's understand Temporal Dead Zone in JavaScript.

If you are confused and are trying to understand what Temporal dead zone is in JavaScript, then let me help you understand TDZ(Temporal dead zone). First we have to understand how hoisting works in JavaScript. Hoisting is the functionality of JavaScript to move declarations at the top of the scope. Lets look at an example,

{
 console.log(my_name);
  var my_name = "swapnil";
}
-> undefined

Here within the scope I have declared a variable my_name and set it to "swapnil", but l have used the variable before declaring it, so what happened? We are getting the output "undefined". The reason is that the my_name has been hoisted and thus the declaration is moved at the top of the scope and is been initialized to undefined. Lets look at an another example

{
my_name = "nil";
console.log(my_name);
var my_name = "swapnil";
}
-> "nil"

Since my_name has been hoisted therefore the my_nil as "nil" is consoled. Now lets try this using let/const keyword

{
console.log(my_name);
let my_name = "swapnil";
}
-> //Reference Error

As you can see we are getting a Reference Error which says the variable is used before declaration. This happens because the variable is hoisted but not initialized as contrary to var keyword and because of this we cannot access or use this variable until initialized. As soon as the variable is initialized the temporal dead zone ends and the variable can be used.

{
// temporal dead zone
// temporal dead zone
// temporal dead zone
let my_name = "swapnil"; // temporal dead zone ends
console.log(my_name); 
}
-> "swapnil"

Summary

So to summarize, TDZ(Temporal dead zone) means variable declared with let/const keyword are temporarily dead and cannot be accessed until its declaration which ends the temporal dead zone.