So in this one, we are declaring the variable.
Then we call the function at increment().
Then the function cycles through and when done, we jump out of the function.
Then the alert(i) returns the result.
Here’s what I don’t understand. Since JS is run from top to bottom, why doesn’t the position of increment() immediately after the function cause the script to form an endless loop? Why does function increment() execute and then jump the increment() call and go right to the alert?
The only thing I can think of is that the function is happening in the place of the call to the function.
You can think of the increment function as being a separate script that before execution is set aside. I have illustrated that with the global object. You can also see it has an i, which is yet to be initialised (no value). This process is referred to as hoisting.
Thread of execution
i is given a value of 0
The function increment is invoked.
The function increment had no i of it’s own, sources it via the scope chain finding it in the global object, and again sets it’s value to 0
step 3 is repeated, but this time i is increased by 3
The function increment returns.
The alert function is invoked passing in the value of i