Hoisting the variable and function: Part 1

What will be the output on line 1, 9 and 6 for below code snippet?

Figure 1: Original code snippet.

Do you have output in your mind?
You think it is: Undefined, Sachin Tendulkar, Sachin Tendulkar?
No! That is not the answer.

Just wait for an answer.

I will explain you my understanding of the JavaScript engine that executes this code. Usually, the engine must be executing this code in multiple iterations and NOT line by line, The Interpreter way.

But, we heard JavaScript is interpreted language!

The line# 3 var who = “Sachin Tendulkar” consists of variable declaration and initialization. At runtime, this line would be rewritten by the JavaScript engine as separate operations refer to line# 3 and #4 in figure 2.

The same rule is applicable to line# 10 in figure 1. It will be represented by the engine as shown in figure 2 (line# 11 and 12).

Figure 2: After separating declaration and initialisation.

Along with separating declaration and initialization, the JavaScript engine would do hosting for variable declarations and functions.

It keeps initializations intact. So line# 3, the variable declaration would be moved to the top as shown in figure 3 (line# 1). Similarly, the function is hoisted before the final execution. The code for JavaScript engine would look like:

Figure 3: After hoisting the variables and function.

Now try to execute code in figure# 3 and see the outcome.

Side by side comparison

Figure 4: The execution.
I hope that helped you to figure out the outcome.