Hoisting in Javascript

Meredith McIntosh
3 min readJan 24, 2021


What in the world is hoisting, you ask? Good question. Hoisting can often overlooked by developers, myself included, but it can be a helpful concept if understood. This is what MDN has to say about hoisting —

Conceptually, for example, a strict definition of hoisting suggests that variable and function declarations are physically moved to the top of your code, but this is not in fact what happens. Instead, the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

Thanks MDN, but Leslie Knope and I both agree that the above definition is still kind of confusing! From my research and understanding, MDN is basically saying that even if you call the function before it is declared, Javascript will look at the functions first before they are called. Javascript rearranges your code in memory and puts the functions at the top of the file.

Hmm.. let’s test the theory out in code and see if that can help with understanding.

Below, I wrote a function first and then called the function afterwards. The results are not too surprising.

The above code totally makes sense!! Of course if the function is written and then called, the code should work properly! But, if hoisting really works the way MDN says it does, if I call the function before the function is written, the code should still work properly. Let’s try it out!

Well look at that! Even if the functions are called before they are actually written, the code will still perform correctly! Wowza!

This is very cool and exciting, but some hoisting rules to keep in mind.

  • Javascript only hoists declarations, not initializations. Example below-
  • In the example below, there is only an initialization, so there will be no hoisting -
  • One more piece of hoisting that I think is important is initializations with let and const are also not hoisted. This is the error that is given with the code below -

Some developers don’t really utilize hoisting and would rather call the function after the function has been written. But on the other hand, some developers like to call all the functions at the top of the file so they can see very quickly what the file does and then, if they want more specific details about a function, they can go to the function to see what it does. Luckily for us, it is up to us to decide how we would like to organize our code. You do you!

Thanks for reading and happy coding!

Let’s connect on LinkedIn!

Documentation —