Open In App

What is the Temporal Dead Zone in ES6 ?

Last Updated : 11 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Introduction: Before going to start, just think about what these 3 words are saying? Temporal means something temporary, not permanent, and Dead means something which is not working or can say it is in a lifeless state, Zone denotes an area but here we are in programming so this term area will be something related to memory, or also zone can be thought of as the time period or phase. So merging these terms narrates that some entity is temporarily in a lifeless or inactive state and cannot be used for any kind of work. You should have knowledge of let and const keywords in javascript to understand the topic easily.

Why temporal dead zone exists?

This question may arise that they are not in earlier javascript then why we need them, And why ECMAscript introduced this additional thing in new updates, actually in programs accessing the variable before assigning a value is bad, Ok let’s say javascript has given some space to variable in memory just because there is a specific reason that you may be going to store some data there, then why to extract that data before actually putting. Most of the programming languages have different configurations for this scenario, like C++ stores garbage before initialization, python variable even doesn’t get created before initialization, and java stores a default value.          
So javascript has undefined but because of the memory allocation phase hoisting of variables takes place and during the thread execution phase we can access them, consequently, the value appears as undefined. Later when the let & const were introduced they have some restrictions for accessing just to help javascript developers write good code and make debugging easy and so the new concept of temporal dead zone came along, it helps us to catch errors because accessing some data before providing is wrong. This is a language construct that saves us from a lot of unexpected errors.  

Now let’s understand with different examples.

 

Example 1: In this example, we are simply using a javascript code snippet and using the var keyword to see how the memory allocation takes place.

index.js




<script>
    console.log(x);
    var x = 6;
    console.log(x);
</script>


Output:

Explanation: 

  1. First of all the Global execution context will be created.
  2. And then the memory allocation phase starts, During this, the variable x got a place in memory and javascript puts undefined there.
  3. And then the thread execution phase starts, During this console.log(x) statement executes and prints the value store in x, which is undefined.
  4. In the next line, there is x assigned to 6, and the undefined value of x gets replaced by 6.
  5. Again at the next console.log(x), x gets printed as 6.

Example 2: Now let’s test out the same code snippet by using the let or const keyword.

index.js




<script>
    console.log(x);
    console.log(z);
    var x = 6;
    let z = 6;
    console.log(x);
    console.log(z);
</script>


 

Output:

Explanation:

  1. First of all the Global execution context will be created.
  2. And then the memory allocation phase starts, During this, the variable x got a place in memory and javascript puts undefined there.
  3. And then the variable z gets space in a different place of memory and same as variable x then undefined will be assigned as value.
  4. Then the thread execution phase starts, During this console.log(x) statement executes and prints the value of x, which is undefined.
  5. In the next line, there is console.log(z), javascript will throw ReferenceError and the program will stop here.

Scope of Variables: Now let’s see the scope where these variables are stored, notice the var x is undefined and stored inside the global object and the let z is also undefined but stored at another place named Script, It means they both are not the same and the javascript engine wants to differ something during their access. The let and const variables are not accessible before they are initialized with some value, and the phase between the starting of the execution of block in which the let or const variable is declared till that variable is being initialized is called Temporal Dead Zone for the variable. And during this zone javascript will always through a reference error if anyone tries to access those variables. 

Example 3:  In this example, we will see the variables which are in temporal dead zone.

index.js




<script>
 console.log("Program Started and Variable z is in Temporal Dead Zone");
 console.log("Variable z is in Temporal Dead Zone");
 console.log("Variable z is in Temporal Dead Zone");
 console.log("Variable z is in Temporal Dead Zone");
 console.log("Variable z is in Temporal Dead Zone");
 let z = 6;
 console.log("Now Variable z is not in Temporal Dead Zone");
 console.log(z);
</script>


 Output:

Explanation:

  1. In the starting, During the memory allocation phase of the global execution context, the let z will get space in memory inside the script object.
  2. During the thread execution phase, the first line of console.log() will execute,  And the z will be in the temporal dead zone also there will be undefined inside that.
  3. From lines 2 to 5 the variable remains in a temporal dead zone.
  4. But as soon as at line 6 we initialize variable z with 15, It no longer remains in a temporal dead zone.
  5. One more point, You might be thinking of that, assigning undefined to z later in the program will make the variable again in the temporal dead zone, No it is only for the initial time. Also, it is not a good practice to assign something as undefined because javascript has a special meaning for that keyword so don’t play with it, otherwise, you may face unexpected errors.

Way to avoid the most common reference/type errors and other errors due to temporal dead zone:

The most efficient way to overcome the errors of temporal dead zone is to initialize the variables at the top of the scope so that when our code starts running it completes the initializing part at first and then use those variables otherwise you can run into a lot of unexpected errors in JavaScript code.

Let’s see an example-

main.js




<script>
   var x = 6;
    let z = 6;
    console.log(x);
    console.log(z);
    console.log(x);
    console.log(z);
</script>


[/div]

Output:

Here x and z are initialized at first



Similar Reads

Temporal dead zone in JavaScript
The Temporal Dead Zone (TDZ) is a concept in JavaScript that relates to the hoisting of the variables and the visibility of variables declared with let and const. In the TDZ, a variable exists but it cannot be accessed until it is not declared. This prevents the variable from being used or accessed before a value is assigned to it. Example: To demo
1 min read
Moment.js moment().zone() Method
The moment().zone() method is used to specify the given Moment object's time zone offset in minutes. An optional parameter can be passed that preserves the current time value and only changes the timezone offset. Syntax: moment().zone( Number | String ); Parameters: This method accepts a single parameter as mentioned above and described below: Numb
2 min read
How to filter an array of objects in ES6 ?
In this article, we will try to understand how we could filter out or separate certain data from the array of objects in ES6. Let us first try to understand how we could create an array of objects by following certain syntax provided by JavaScript. Javascript Array of Objects: The array of objects helps any user to store multiple values in a single
4 min read
ES6 RegEx
A RegEx is the short form of the Regular Expression, which is the sequence of characters that define a pattern. The characters in a RegEx can be alphabets, numbers or special characters. Usually, RegEx is used to find a pattern in a string to replace, delete or modify them. In ES6, a RegEx can be defined by 2 different notations. Literal notation:
3 min read
Arrow operator in ES6 of JavaScript
ES6 has come with various advantages and one of them is the arrow operator. It has reduced the function defining code size so it is one of the trending questions asked in the interview. Let us have a deeper dive into the arrow operator's functioning. Syntax: In ES5 a function is defined by the following syntax: function functionName(arg1, arg2….) {
4 min read
ES6 Top features and syntax
ES6 or as it is officially called: ECMAScript2015 is a new JavaScript implementation and is arguably the hottest topic in the JS developer's conventions and meetups why it should not be: JavaScript rules the web and is gaining a foothold in every other field possible, be it robotics(nodebots), desktop applications(using ion framework), chatbots, et
3 min read
ES6 Promises
Promises are a way to implement asynchronous programming in JavaScript(ES6 which is also known as ECMAScript-6). A Promise acts as a container for future values. Like if you order any food from any site to deliver it to your place that order record will be the promise and the food will be the value of that promise. So the order details are the cont
4 min read
Motivation to bring symbols in ES6
Javascript comprised six datatypes undefined, null, boolean, String, Number and Object (includes array datatype). The Symbol is newly introduced datatype in ES6 also known as JavaScript 6, which makes the total number of data types in JavaScript is 7. It is a primitive datatype which means Symbol cannot be instantiated. Symbols are immutable dataty
3 min read
ES6 | Array filter() Method
The Array filter() is an inbuilt method, this method creates a new array with elements that follow or pass the given criteria and condition. Few Examples have been implemented below for a better understanding of the concept Syntax: var newArray = arr.filter(callback(element[, index[, array]]) [, thisArg]) Parameter: This method accepts 2 parameters
2 min read
ES6 Math
The ES6 Math object contains so many properties and methods to perform some mathematical functions. The ES6 is an object that can be called without creating it. With the help of ES6 Math in JavaScript, you can store integers in the form of binary and octal notation. There are so many properties and functions available in ES6 Math. Also in the funct
4 min read