Sign in
Log inSign up

What Is Temporal Dead Zone(TDZ) in JavaScript?

Why TDZ is important and how it helps us catch errors. let's understand the concepts more clearly.

Isha's photo
Isha
·Jan 9, 2022·

2 min read

What Is Temporal Dead Zone(TDZ) in JavaScript?

Photo by Anete Lūsiņa on Unsplash

A Dead zone? Sounds like a Sci-fi movie thing but to know the details is always good to understand. So, let's start with the most basic part.

What do we use to add a level of scope in javascript?

{{{{ var isha = true}}}}

So here is the short story from history, In the stone age, Everyone knew only one thing to declare a variable and that is by using var. then one fine day, a group of nomads with a leader named "ES6" bought two stones 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.

     let ishaScore = 1;
     let isAlive = true;
     if (isAlive) {
         let ishaScore = 2;
      }
     console.log(ishaScore); // This gives output as 1

In contrast to the above code, var declaration has no block scope:

     var  ishaScore = 1;
     var  isAlive = true;
     if (isAlive) {
        var  ishaScore = 2;
      }
     console.log(ishaScore); // This gives output as 2

One more difference between let/const and var is that if we access var before it's declared, it is undefined. But if we do the same for let and const, they throw a ReferenceError.

console.log(varIshaScore); // undefined
console.log(letIshaScore); // Doesn't log, as it throws a ReferenceError
                                            // letIshaScore is not defined

var varIshaScore = 1;
let letIshaScore = 1;

They throw the error all because of the Temporal Dead Zone.

What Is TDZ?

A temporal dead zone (TDZ) is the area of a block where a variable is inaccessible until the moment the computer completely initializes it with a value.

Why does the TDZ exist between the top of the scope and the variable declaration? What's the specific reason for that?

It's because of hoisting. The JS engine that is parsing and executing our code has only 2 simple steps to do.

  1. Parsing of the code into executable byte code. (Where hoisting happens which will move all our variable declarations to the top of their scope.)

2.Run time Execution.

Why TDZ?

Dr. Axel gives an amazing idea to the question in this post

In short, the main reason is it helps us catch errors. To avoid the issuesTDZ causes, always make sure you define your let and const at the top of your scope.

Happy Learning.

Isha.

Hassle-free blogging platform that developers and teams love.
  • Docs by Hashnode
    New
  • Blogs
  • AI Markdown Editor
  • GraphQL APIs
  • Open source Starter-kit

© Hashnode 2024 — LinearBytes Inc.

Privacy PolicyTermsCode of Conduct