DEV Community

Cover image for What is the Temporal dead zone?
Aayush Jain
Aayush Jain

Posted on

What is the Temporal dead zone?

In case of let and const variables, Basically, Temporal Dead Zone is a zone "before your variable is declared",
i.e where you can not access the value of these variables, it will throw an error.


let sum = a + 5;        //---------
//some other code       //         | ------>  this is TDZ for variable a
                        //         |
console.log(sum)        //---------
let a = 5;
Enter fullscreen mode Exit fullscreen mode

above code gives an error

the same code will not give an error when we use var for variable 'a',


var sum = a;                            
console.log(sum)     //prints undefined
var a = 5;
Enter fullscreen mode Exit fullscreen mode

let and const have two broad differences from var:

1.They are block scoped.
2.Accessing a var before it is declared has the result undefined; accessing a let or const before it is declared throws ReferenceError:

console.log(aVar); // undefined
console.log(aLet); // Causes ReferenceError: Cannot access 'aLet' before initialization

var aVar = 1;
let aLet = 2;
Enter fullscreen mode Exit fullscreen mode

It appears from these examples that let declarations (and const, which works the same way) may not be hoisted, since aLet does not appear to exist before it is assigned a value.

That is not the case, howeverβ€”let and const are hoisted (like var, class and function), but there is a period between entering scope and being declared where they cannot be accessed. This period is the temporal dead zone (TDZ).

To Summarize

let,const,var are all get hoisted process.
(whats mean they go upper and declare in the top of the scope.)

hoisting process: var, let, const
Initialisation process: var

Thanks, and see you next time!

Top comments (0)