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.
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:
- Compilation ( Creation ) Phase
- 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.
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 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.
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 ๐.