The flow of Code Execution in Javascript

Javascript is a language designed for the Web, Everything that happens in it, happens in an Execution Context. If a program runs in javascript an execution context is created. Everytime an execution context is created it is created in two phases.

Creation Phase or Memory Creation

When Memory creation occurs, javascript allocates the memory to all variables and functions present in the program. The function calls and references are stored for later use and the variables are stored with a value of undefined at the start.

So when this phase ends, all variables have been scanned and made undefined for and functions are kept.

Code Execution Phase

In this phase the main execution takes place and the javascript runs the code line by line. When a new function is invoked a new execution context is created within the Global Execution context

These two phases are repeated until the call stack is empty.

What is a Call Stack?

Imagine a pile of books, a very tall pile of heavy books. If you try to get something at the bottom it will be very difficult and you might end up crashing the tower of those heavy books. So what do you do? You take the book on top and remove it and keep doing this until you reach your desired book. The same thing is happening in the call stack. The term LIFO stands for Last In First Out, which simply means the book you kept last on the top of the pile needs to go out first

function A(){
    B()
    console.log(`I am Function A`)
}
function B(){
    C()
    console.log(`I am Function B`)
}
function C(){
    console.log(`I am function C`)
}
A()

image.png

Now in the above example you can see the function C ran first then function B and then finally function A. Image below explains this further.

2.png

The blocks in the above image are functions that were pushed into the call stack.

  • First the program was scanned and it saw only function A is being called so it went to Function A

  • In Function A it saw the call for Function B before the console.log could execute so it went to Function B and added it in the call stack, and from there to Function C and added it to the call stack.

  • Entire functions are loaded and stacked on top on one another and so we execute the one at the top, In this case its Function C.

  • After the execution of Function C, the next function in the call stack was Function B so it went ahead and executed the console.log there.

  • And finally, it executed the last function remaining in the call stack which emptied the call stack.

Did you find this article valuable?

Support Ashish Kr Jha by becoming a sponsor. Any amount is appreciated!