Hoisting in Javascript

Hoisting in Javascript

Gulshan Yadav

Published on Sep 13, 2021

3 min read

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

Hey, you are back again!

In my previous articles, we have discussed some of the basic terminologies in JavaScript.

In this article, we'll be learning about hoisting in JavaScript.

So what is hoisting?

Hoisting refers to the process where the interpreter allocates memory for a variable or function before its execution.

In simple words, a variable or function can be used before it is declared.

I hope you are clear till here.

Let's start with,

Variable hoisting.

As per the above definition, we can use a variable before declaring it.

So let's try it.


var Gulshan = 100;

And that's it, run this code, and you will get an output of 100 without getting a Reference error.


Variable Hoisting

I hope you're clear till now.

Let's understand function hoisting.

If you understand the previous topic. i.e. variable hoisting.

I want you, to try it on your own now.


Function hoisting.

I want you to apply the above definition again.

Function hoisting means that a function can be used before it is being executed.

Example code:


function somefunction(){



Like the previous code, this piece of code will work too without any error.


Function Hoisting

You may ask, how all this works?

JavaScript interpreter defines all these variables and functions at the top of the program.

Is it a good practice?

Nope, this makes code confusing to read because you will find it harder to read the code when your code grows big in size.

So you should declare your functions and variable at the top.

And hoisting doesn't add any performance benefits too.
So it doesn't make any sense to use hoisting if you don't want to blow up your mind in fixing bugs.

Advantages of hoisting


No .

It is convenient. Both to the reader of code as the coder. Not so much for variable hoisting, but function hoisting.

This way, you can put the helper functions to the bottom of your code and the more abstract ones, which show your business logic at the top.

Disadvantages of hoisting

You can access them before they are declared. In such a case, their value would be undefined though, as only declarations and not initializations are hoisted.
Therefore it is generally considered a bad practice.

In my forthcoming article, I won't be covering all the basics. There are more great articles than mine.

You can find a ton of knowledge here, MDN Docs

In future articles, I'll be demonstrating to you how to write javascript programs.

I won't be touching web development as of now. We will be doing scripting, scraping, and many more using JavaScript (Advance mode)

Until I come up with another article,

Stay safe and happy coding.

Cya ๐Ÿ˜„

Share this