JavaScript : Temporal Dead Zone

JavaScript : Temporal Dead Zone

Hey Beginners, Lets Understand the Temporal Dead Zone of let and const variables in JavaScript

As we all know that, Whenever we run any JavaScript Program A Global Execution Context is created and in its memory component, All the Variables declared with "var" are assigned a special keyword called "undefined". So, if we try to access that variable before its declaration, it will output "undefined" (due to Hoisting) which is totally fine. But, In case of "let" and "const" variables, the Scenario changes. These variables do not get assigned with any value or keyword. Therefore, When we try to access them before there declaration, It will give us a "ReferenceError". Thus, as we are unable to access these "let" and "const" variables before there declaration, these variables are said to be in Temporal Dead Zone till they are declared and initialized. After that, they are out of the Temporal Dead Zone. let us understand this through some examples. Note that Temporal Dead Zone starts from beginning of the scope till the declaration and initialization of let and const variables.

  console.log(a);  //undefined
  console.log(b);  //referenceError: cannot access b before initialization
  console.log(b);  //referenceError: cannot access c before initialization

  var a = 15;
  let  b = 25;
  const c = 35;

In the above code snippet, As variable a is declared and initialized using "var" it got assigned with "undefined" and the variables b and c are declared and initialized using "let" and "const" therefore, due to temporal dead zone we cannot access them before their declaration and initialization.

function getValue(){
console.log(a);
}
getValue(); // ReferenceError: Cannot access 'a' before initialization
let a = 15;  // temporal dead zone for variable a ends here
getValue();  // output : 15

In the above code, initially the function getValue is declared and after that it is called once before the declaration and initialization of variable a and again called once after the declaration and initialization of variable a. Now, as we know the let and const variables are in Temporal Dead Zone till they initialized. So, when getValue() is called before initialization of a, due to temporal dead zone it will output referenceError. On the other hand, when the getValue() is called after the initialization of a i.e. out of the Temporal Dead Zone, the output will be the value assigned to a i.e. 15.