Temporal Dead Zone in JavaScript (original) (raw)

Last Updated : 1 Feb, 2025

The Temporal Dead Zone refers to the period between the entering of a scope and the actual declaration of a variable using let or const. During this period, the variable is in an "uninitialized" state and accessing it will result in a ReferenceError.

Understanding Variable Hoisting

To grasp TDZ, it’s important to understand hoisting. Hoisting is JavaScript's behaviour of moving variable and function declarations to the top of their containing scope during compilation.

**Hoisting with var

JavaScript `

console.log(a); // undefined var a = 5;

`

Here, a is hoisted to the top of its scope and initialized with undefined, so accessing it before the declaration doesn’t throw an error.

**Temporal Dead Zone with let

JavaScript `

console.log(b); // ReferenceError: Cannot access 'b' before initialization let b = 10;

`

In this case, b is hoisted but not initialized, so accessing it before the declaration results in a ReferenceError.

Examples to Illustrate Temporal Dead Zone

**1. Accessing let and const Before Declaration

JavaScript `

function gfg() { console.log(x); // ReferenceError let x = 3; } gfg();

`

2. Block Scope and TDZ

JavaScript `

{ console.log(y); // ReferenceError const y = 7; }

`

3. Variables Declared After a Condition

JavaScript `

if (true) { console.log(z); // ReferenceError let z = 9; }

`

4. No Temporal Dead Zone with var

JavaScript `

{ console.log(a); // undefined var a = 5; }

`

Understanding the Flow of TDZ

The Temporal Dead Zone works in the following manner

Why Does Temporal Dead Zone Exist?

Practical Use of TDZ

For writing the clear and error-free code, it is important to understand the practical use of the TDZ. Below is shown how you can practically use TDZ