DEV Community

arpitashrivastav
arpitashrivastav

Posted on

What is Hoisting in JavaScript?

Introduction

Image description
Did you note that in the preceding example, we declared a variable after the console.log of x and invoked the function before declaring it? But wasn't this a surprise given that we received undefined for a variable and the output of function but not an error?

So if you didn't know this then let's learn about hoisting
in JavaScript.

A phenomenon in JavaScript by which we can access variables and functions before declaring it, is known as hoisting.

How this happens?

This is because the variables are already assigned with a spatial value of undefined in the memory space during the memory creation phase.
In the case of functions, the entire code is kept in memory space.
Thus because they are stored during the 1st phase which is the memory creation phase, is the reason we don't get any error when we run the code.

Are Arrow functions hoisted?

Image description
As we can see that when we attempted to invoke the getName function before declaring it in the arrow function, we received a TypeError, indicating that getName is not a function.

This occurred because when we attempted to execute this arrow function, it issued an error since it operates similarly to a variable. So, just as variables are allocated as undefined in a memory space, arrow functions are also allocated as undefined in the memory space during the memory creation phase.

Are let and const hoisted?

Yes, let and const are hoisted, but not in the same way that var declarations are. So, if we try to access let and const before declarations, we receive a ReferrenceError that states they are not defined.

Image description

So how will we know they've been hoisted?

So it is because we have var x in the global scope whereas a and b are in a different scope, which is script.

So in the memory creation phase even a and b are assigned an undefined spatial value in the memory space, but it is just saved in another memory space.

So they've been hoisted, but why are we still getting a ReferrenceError?

This is because let and const are hoisted but they are in the Temporal Dead Zone for the time being.

Temporal Dead Zone

The time period between the variables being hoisted to until they are assigned a value is known as the temporal dead zone.

As we can see below, we initialised the variable at line 3, hence anything above line 3 was the temporal dead zone for a.

Image description

So, based on the information provided above, we can deduce that hoisting occurs in conventional function declarations and variable declarations of var let and const, however there is a variation in behaviour with let, const, and var.

Thank you for taking the time to read this.
I hope you found this useful.

Top comments (0)