DEV Community

Naveen710
Naveen710

Posted on

Temporal dead zone

what is the temporal dead zone?

Temporal Dead Zone is the time period between which a variable is inaccessible, to the point where it is initialized. To know it better, we first need to dive a bit into a concept called hoisting

HOISTING

In JavaScript all the variables, let it be initialized with let , var or const are hoisted. Hoisting refers to the process whereby the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, prior to execution of the code. So every variable declared anywhere in the code is moved to the top of the scope by the interpreter before execution of actual code even begins. now, hoisting is different for var and let, const.

In var, the variable gets hoisted in the global object and no TDZ is faced but in let and const the variable is hoisted in script scope and given a memory location that cannot be accessed before initializing the variable. this causes TDZ in let and const.

example:

console.log(a);  // here 'undefined' will be consoled as no TDZ occurs in var
var a=3;

Enter fullscreen mode Exit fullscreen mode
console.log(a);// here TDZ occurs and Reference error is thrown
console.log(b);//gets undefined 
let a=3;
var b=5; // now a is initialized
console.log(a); // No TDZ .
Enter fullscreen mode Exit fullscreen mode

Since in the second example we declared let after the calling so TDZ occurred. A reference error is thrown for the same as we are using the variable before it is initialized and var don't throw any error as we are calling it even before initializing it that is because of hoisting

Top comments (0)