Advance JavaScript: Why hoisting?
Many of us might have heard about the term hoisting in JavaScript, some of us might also be clear with it but few of us know why it actually happens.
If you are not clear with what it is and how it affects our code, please refer my another article here.
In this article, I would like to put some light on why this specific behavior is observed in javascript. Hoisting has everything to do with how our code is interpreted and executed by the JavaScript interpreter.
During run time, javascript code is interpreted in a minimum of 2 cycles, I would rather call it phases.
1st phases > completion or compilation.
During 1st run, the interpreter goes through the code line by line while looking only for functions or variable declarations. Wherever it encounters a declaration, it moves it to the top.
This is how the interpreter will get an idea about which functions and variables are going to be used in the current context, also how much approximate memory it will be needing to execute the current function. Further, it also helps in creating variableObject for Execution Context right before execution of function starts.
Below things are skipped during this phase:
1. Variable and functional assignments.
2. ‘class’ declarations.
3. code statements.
4. function calls
2nd phase > execution.
During 2nd run, the compiler starts the execution of output from the previous run. Now it will start compiling the code in a normal way i.e. assigning values, executing function calls, reassignment of values, etc.
To understand it more, please refer below code snippets and their explanation:
Talking about precedence from the above examples,
1. Function declaration takes precedence over the variable declaration.
2. The variable assignment takes precedence over function declaration.
Hope it would have helped you to know more about javascript interpreter and more important, dealing with tricky questions around hoisting during the interviews.