What is Temporal dead zone?

What is Temporal dead zone?

In simple word, when we declare a variable using let or const keyword but try to access before it is declared and initialized. This dead zone starts from the code-block where it is started. A simple code snippet to understand.

console.log(`I am variable a = ${a}`);
let a = 10;

If we try to run the above code, it will throw an error and the error is ReferenceError. Let's look at the image.

ReferenceError

Actually, it is almost the same error when we try to access a variable which is not declared yet. Just like below one.

console.log(`I am variable x = ${x}`);

But here comes a twist my friend. It is not exactly the same thing. Let see another code.

console.log(`I am variable x = ${x}`);
let x = 50;

Now copy this code and paste in a HTML page in script tag or make another app.js file and link this file with any basic HTML page to see what was happed there.

At this point, run the HTML file with browser. Open the browser devTool then watch out for source. If you put a debugger at the top of the script or on console.log(), you will see that x is already in script scope not on global scope. Just like below image.

Source/scope

We can say that the variable x is already hosted or in programming term hoisted. But we cannot access this at the very first of the code-block until it is initialized. And this time span of before initialization is temporal dead zone.

Now try with another code snippet which have the variable keyword var.

console.log(`I am variable b = ${b}`);
console.log(`I am variable q = ${q}`);
var b = 35;
let q = 7;

If you go to browser's source again with this code snippet. Let's see the images.

source/highlight

source/undefined

As we do it before, just put the debugger at the very first of the code-block and run again. Now go to browser console. We can see b is printed undefined means its value. But as we know q can't be printed.

We can see that b is in global and q is in script.

Finally, come to a conclusion is that if we declare any variable using let or const it will be in sleeping mode or dead for a while. And also, can be said that the time span of before initialization is "Temporal Dead Zone".