What The T. D. Z. !

Understand Temporal Dead Zone with code samples.

ยท

3 min read

TEMPORAL DEAD ZONE

You read the title right. Even pro developers forget this aspect of JavaScript sometimes.

But let's take a look at why does it even happen in the first place quickly.

var:

  1. Before ES6, variables were declared using var which never lead to TDZ.
  2. var's scope was working regardless of the block of the code where it was used.

For example:

var a = 5;
if(true){
  var a = 10;
  console.log(a); //this returns 10
}
console.log(a); // even this returns 10

let and const:

This same example works differently with let and const :

let a =10;
if(true){
  let a = 20; 
  console.log(a); //this returns 20
}
console.log(a); // this returns 10

This is how let and even const works in a particular block scope.

Now lets discuss about the TDZ aspect of let and const:

Lets see these two scenarios:

Scenario 1 with var:

console.log(a); // Guess what could be the answer

var a = 10;

This returns undefined. Not an error. Because a can be accessed anywhere in the code and it won't throw an error , only in var though. But the actual value shows up only when you use it after initializing it with a value. Not before that. This concept is called hoisting.

Scenario 2 with let or const. TDZ works almost similarly for both of these :

function foo() {
                      //0
  console.log(a);     //1
  let a = 20;         //2
  console.log(a);     //3
}

let b = 30;           //4
console.log(b);       //5
foo();                //6
console.log(b);       //7 Guess answers till here for all logging statements.

Did you guess :

30
Uncaught ReferenceError: a is not defined
20
30

That's wrong. Let me explain

When the function foo() was called, the line 1 in the above code entered into TDZ as it was not initialized before using it.

And guess what?

After entering into TDZ, no matter what is the scope of the block or entire code, it won't execute an extra line of code the moment it is in TDZ.

Before entering into TDZ, the line 5 was executed, but not the line 7 which is exactly the same after calling foo() which entered TDZ.

So the actual answer for above code will be:

30
Uncaught ReferenceError: a is not defined

That's it.

Even if the later part of code works fine, it won't just execute the moment if previous code enters into this frightening zone.

The solution for this is everytime you write a block of code, just declare the let and const variables at the top in that block.

If you reached reading till here, I appreciate your feedback on the quality of this blog and areas of improvement.

Stay safe. Keep coding ๐Ÿ˜Ž

ย