DEV Community

vidhi-thakur
vidhi-thakur

Posted on

6 4

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay