Let, Const and The Temporal Dead Zone鈽狅笍

Let, Const and The Temporal Dead Zone鈽狅笍

Okay so I know TDZ seems like an intimidating term in the beginning, but trust me it is not!

So first let's understand the difference between var, let and const.

SCOPE馃攷

1. var

The scope of var is global when it is not declared within a function. And it is local when declared within a function.

var a = "JS";

function testFunction() {
        var b = "I am inside a function";
    }
console.log(a); // Output: JS

console.log(b); // Reference error: b is not defined

2. Let and Const

Let and const declarations are block scoped and are only accessible within the block they were declared.

Redeclaration 馃攣

We can redeclare the var variables within the same scope.


var a= 20;
var a= 23;
console.log(a);

but we cannot do this with let.

let a = 20;
let  a = 23;
console.log(a); // Gives a Syntax Error

-> const needs to be given a value at the time of declaration or it gives a Syntax Error upfront.

const c;
c = 13; // NOT ALLOWED

Hoisting 猡达笍

Hoisting is the process where the interpreter appears to move the declaration of functions, variables or classes to the top of their scope, before the execution of the code.

All variables are hence given the value of undefined.

Let's understand this with an example:

console.log(a); // Output: undefined
var a = 10;
  • Now when we use let or const instead of var,
console.log(b); // This statement will give reference error
let b = 10;

What happens behind the scenes?

  • var

var a declared -> memory allocated -> gets attached to the Global Object

And hence it is available even tho the value 10 is not assigned to it yet.

  • let and const

But in the case of let and const,

let b is declared -> memory allocated-> in a separate memory space

Hence, we cannot access these variables until we give values to them. This is why we get an error.

WHY THIS HAPPENS馃?

This happens because variable 'b' is in the Temporal Dead Zone馃拃 .

The phase from hoisting to getting assigned a value is called a Temporal Dead Zone(TDZ).

We get a reference error if we try to access a variable in TDZ.

Conclusion 馃

All your variables are supposed to be declared at the beginning of your code.