Hoisting Debugged!!!

Hoisting Debugged!!!

Understanding hoisting made easy

ยท

2 min read

Generally, people refer hoisting in JavaScript to the English word hoist which means "lifting". But as it turns out hoisting is not what you think it is.

Untitled.png

Song By Adnan Sami : Lift karadey

Hoisting rather is the process that occurs while JavaScript Engine interprets JavaScript Code

Usually people just starting with JavaScript goes with the understanding that hoisting means moving the code to top of the file. Well this may be right to some extent, but in real world scenarios that's nothing but a mere misconception.

Let's understand it piece by piece.

A Look into JavaScript Interpretation

JavaScript consists of two phases viz:

  1. Compilation ( Creation ) Phase
  2. Execution Phase

But prior to this JS code is interpreted within the Execution Context that it is in. So when we create a JavaScript file a Global Execution Context is created.

table.drawio.png

Compilation ( Creation ) Phase

During compilation phase, JavaScript scans through all the code and selects specific keywords let, const, var, function, class before any of the other elements and assigns space in the memory to each of them.

You can picture it this way, rooms being given to the selected lucky draw winners ezgif.com-gif-maker.gif Okay seriously, I need to stop making random pun! ๐Ÿ˜…

When compiling these keywords as mentioned JavaScript assigns unique space for each declared variable. This process of "lifting" is referred to as hoisting.

So, there goes the misconception that hoisting means moving (or lifting) variables and function to the top of their (global / function) scope.

pumped-weights.gif I Promise this was the last one ๐Ÿ˜

What exactly happens is that during compilation phase declared variables and functions are looked out for before the rest of the code, thereby creating a notion of "lifting".

Execution Phase

After compilation phase i.e. after hoisting, the second phase begins. JavaScript interpreter now again scans through all of the code from top but now it also processes all the variable values and functions it encounters during parsing.

Learnt something new? Make sure to leave your feedback ๐Ÿ˜‹.

ย