DEV Community

vidhi-thakur
vidhi-thakur

Posted on

Temporal Dead Zone (TDZ)

hello

Let's understand TDZ and why does it exist.

Temporal Dead Zone (TDZ) is an area of a block where a variable cannot be accessed until it is initialized. Let's see a simple example to understand better.

Example 1

console.log("Welcome ",name)

let name = "Vidhi"
Enter fullscreen mode Exit fullscreen mode

In the code written above, the area above the variable name is initialized is temporal dead zone. Notice a console log there. Well if we try to run this code, it will throw a reference error.
TDZ error example

This happened because in the console.log statement we tried to access a value which was not yet initialized. Let's see one more example.

Example 2

console.log("Welcome ",name)

var name = "Vidhi"
Enter fullscreen mode Exit fullscreen mode

This example has a small change when compared to example 1. Here the variable is declared with var. Now what it does is, when we run this code, there will be no error but the value of name will be undefined.

This happens because when a var variable is hoisted, it is automatically initialized as undefined. This does not happen with let and const and therefore the error occurs.

Top comments (0)