DEV Community

Cover image for Hoisting and Temporal Dead Zone (TDZ) in JavaScript?
dev-ashishsethi
dev-ashishsethi

Posted on

Hoisting and Temporal Dead Zone (TDZ) in JavaScript?

Hoisting and Temporal dead zone can be difficult to understand in the first try. I will try to make you understand in one of the simplest ways possible please be with me till the end.

First to understand hoisting we will have to understand how does a JS program runs.

A JS program runs in 2 phases:

  1. Memory allocation phase
  2. Code execution phase

Memory Allocation Phase

In a JS program all the variables are allocated only memory not their values and all the functions are allocated with their body.

Code Execution Phase

After memory allocation code execution is done. Code execution is done line by line

Hoisting

Meaning of hoisting in English dictionary: raise or haul up.

Hoisting in JS is also done in same way. When a variable or function is called before it is defined, this is known as hoisting.

Hoisting in case of let and const variables is different from hoisting with var variables

When a var variable is hoisted it gives undefined but when a let or const variable is hoisted it gives ReferenceError

code Example:
In case of var

console.log(bestFood); // returns undefined because bestFood’s TDZ does not exist here
var bestFood = "Vegetable Fried Rice"; // bestFood’s TDZ does not exist here
console.log(bestFood);

In case of let and const

console.log(bestFood); // returns ReferenceError because bestFood’s TDZ
let bestFood = "Vegetable Fried Rice";

This happens because when memory allocation of var variable is done it allocates a placeholder "undefined" but in case of let and const no such thing happens

Temporal Dead Zone or TDZ occurs when a variable is not initialized and you attempt to access a variable before its complete initialization, then it gives a ReferenceError

TDZ ends when you initialize that variable

Functions can also be hoisted.

code example:

catName("Tiger");
function catName(name) {
console.log("My cat's name is " + name);
}

output: My cat's name is Tiger

As you already know that when functions are hoisted then whole body of function is copied in memory allocation phase. So, In case function hoisting it does not give any error.

Top comments (0)