Take the example of this simple program
In line 1, the program saves a function declaration to a variable ‘sayOne’. Note that it only saves the function declaration but does not call it yet. So, at this point, none of its code is actually run and hence line 2 would not get executed yet. In line 5, it saves another function definition to a variable ‘sayTwo’ (but doesn’t call it yet). In line 9, it calls the function sayOne. At this point, the saved function definition of sayOne is executed, which results in line 2 of the program being executed and the value of “1” being printed onto the console. Similarly, in line10, the program calls the function sayTwo, which leads to line 6 getting executed, which prints the value of “2” onto the console.
Let us tweak the above code a bit and try to understand what happens then. Let us add a third function called ‘sayThree’.
Let us now call this function in the code
As you can see, we have called the sayThree function (which prints “3” onto the console) inside the body of function sayOne. Hence, in the execution of the above program, what do you think would happen in line 14 when function sayOne is called? Would the console first log “1” and then move on to executing the code of sayThree, or would it pause its own execution, call the sayThree function, wait for it to complete, and then move on to finally print “1” onto the console?
Well, the output of the above program will be
3 1 2
| | | | | | | | | sayOne() | |____________| Call stack
| | | | | | | sayThree() | | sayOne() | |_____________| Call stack
The program then jumps to the execution of the function at the top of the stack, which is the sayThree function. The code of sayThree function is now run, in which line 11 prints “3” onto the console. The program then sees that it has reached the end of the sayThree function and hence pops it out of the stack. So, the stack now looks like this
| | | | | | | | | sayOne() | |_____________| Call stack
| | | | | | | | | | |_____________| Call stack
| | | | | | | | | sayTwo() | |_____________| Call stack
Since it’s the topmost function in the stack, the program’s execution jumps to that of sayTwo, where in line 7, the value of “2” is printed on to the console. Upon reaching the end of the function, it is popped off the stack and the call stack is now empty. There are no more lines to run and hence the program terminates.
I shall be discussing that and much more in Part 2 of this series.
This post was originally published here on Medium.