My FeedDiscussionsHashnode Enterprise
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Temporal Dead Zone

Temporal Dead Zone

Bipin Yadav's photo
Bipin Yadav
·Jan 11, 2022·

2 min read

Hello friends , in this blog we are going to know more about Temporal Dead zone. What-is-the-Temporal-dead-zone_.png

We know that in JavaScript we can add { } to add a level of scope wherever we want .

Before ES6 there was no other way to declare variables other than var. But ES6 brought us let and const.

let and const declarations are both block-scoped, which means they are only accessible within the { } surrounding them. var, on the other hand, doesn't have this restriction.

Example 1:

let babyAge = 1; let isBirthday = true;

if (isBirthday) { let babyAge = 2; }

console.log(babyAge); This prints 1

In the above example the first babyAge is used but the second babyAge is not used because because it is declared is block scope.

In contrast, the var declaration has no block scope:

example 2 :

var babyAge = 1; var isBirthday = true;

if (isBirthday) { var babyAge = 2; }

console.log(babyAge); This prints 2

The final salient difference between let / const and var is that if you access var before it's declared, it is undefined. But if you do the same for let and const, they throw a ReferenceError. They throw error because of Temporal Dead Zone.

What is Temporal Dead Zone ?

The TDZ is the term to describe the state where variables are un-reachable. They are in scope, but they aren't declared.

The let and const variables exist in the TDZ from the start of their enclosing scope until they are declared.

The only difference between const and let is that when they are hoisted, their values don't get defaulted to undefined.

When variables get hoisted, var gets undefined initialized to its value by default in the process of hoisting. let and const also get hoisted, but don't get set to undefined when they get hoisted.

And that's the sole reason we have the TDZ. Which is why it happens with let and const but not var.

Why do we have the TDZ?

It helps us catch errors.

To try and access a variable before it is declared is the wrong way round, and shouldn't be possible.

It also gives more expected and rational semantics for const (because const is hoisted, what happens if a programmer tries to use it before it is declared at runtime? What variable should it hold at the point when it gets hoisted?), and was the best approach decided by the ECMAScript spec team.

Took reference from freeCodeCamp