DEV Community

Cover image for Understanding Temporal Dead Zone!
Priya Kothalkar
Priya Kothalkar

Posted on • Updated on

Understanding Temporal Dead Zone!

Temporal Dead Zone is the area of a block where a variable is not accessible till it gets initialized with a value.

  • Block is pair of brackets {...} used to group multiple executable statements
  • Initialization means assigning an initial value to a variable

If we try to access the variable before its initialization, it will throw a Reference error as shown below:

Image showing reference error

As you can see we got ReferenceError stating can't access the variable before initialization. To prevent our Javascript code from such kind Errors, we need to access variables outside the Temporal Dead Zone(TZD).

Scope of Temporal Dead Zone:

TDZ starts at the beginning of the block's local scope and ends with the variable initialization with a value.

{
  // tdz of block started
  // tdz of block started
  console.log(a); // Reference Error
  // tdz continued
  // tdz continued
  let a = 20; // tdz ends here
  // tdz does not exist here
  // tdz does not exist here
}
Enter fullscreen mode Exit fullscreen mode

As we can see that this started at the start of the {}(brackets/block) itself and ended with the variable initialization.
We got a Reference error because we tried accessing the variable before its initialization. So, it's a good practice to access variables after initialization.

Let's take examples to better understand the concept:
  • Example 1: Accessing variables after declaration and before initialization
let add;
console.log(add);
Enter fullscreen mode Exit fullscreen mode

The above code gives us the output as undefined :

output-undefined

The output shows that we have that variable but do not have any value assigned yet, so the compiler gives it an undefined value.

  • Example 2: As we know if we try to access a variable before its definition and initialization it will give a reference error.

Image showing reference error

  • Example 3: If we use var to declare a variable we get undefined as output, as we try to access the variable before initialization.
console.log(add);
var add = 3;
Enter fullscreen mode Exit fullscreen mode

Output:

var-output-undefined

Javascript does not initialize let and const variables with any values, they remain dead and inaccessible. In contrast, var is initialized after its hoisting.

Nowadays let and const are used instead of var to define variables as it causes minimum consequences.In old scripts only we would be able to see var used.

Top comments (0)