DEV Community

Cover image for How Javascript Code is Executed and Call Stack?
Lawaanu Borthakur
Lawaanu Borthakur

Posted on • Edited on

How Javascript Code is Executed and Call Stack?

JS Code Eg
When the above javascript code is run, a global execution context is created. If you want to know about execution context refer to my earlier post.

Execution Context is created in two phases.
1st Phase: Memory Creation Phase 2nd Phase: Code Execution phase

In Memory Creation Phase which is first phase when we run the code, Javascript will run through the whole code from top to bottom line by line and allocate memory to all the variable and functions.
Execution Step1
the variables i.e n and squareNum stores a special value called undefined in memory space in this phase and in case of function it stores whole code of the function in memory space.

In Code Execution Phase which is the second phase, Javascript will again run through the code from top to bottom line by line. In this phase all calculation and functions are done.

Execution Step 2

Now in this phase, first line of code is executed and value of n is changed to 2 from undefined
In line number 2-6 of the code in the above image there is nothing to execute. So,it goes to line number 7

In line number 7 ,it is a function invocation code i.e var squareNum=square(n);.So, everytime a function is invoked a new execution context is created. The reason is that the functions are like mini programs.
Execution Step3
In the similar manner there is memory creation phase and code execution phase in this new execution context which is created because of function invocation.
Memory Execution Phase of new execution context

Execution Step 4
In Code Excecution Phase of new execution context the value of num is changed to 2 from undefined.I.e n=2 is passed to num in line number 2 of the code.
Execution Step 5
In code execution phase then the calcution i.e num*num is done in line number 4 and the value is placed into ans variable
Execution Step 6
Now in line number 5 return statement is there this return ans; means return the control of the program where the function was invoked i.e to line number 7

Execution Step 7
Now as the execution is over so, the new execution context which was created while function invocation will be deleted.

Execution Step 8
After all execution is over then the global execution context also gets deleted.

So,this is how the Javascript code is executed.

Few extra points to keep in mind.

Note:every execution context is put inside a stack which is called as call stack so that it executes in a sequential order.

“Call Stack Maintains the order of execution of Execution Context”

Call Stack
Once the execution is over. The execution context is popped out i.e remove from the stack.

Call Stack also known as
1)Execution context stack
2)Program Stack
3)Control Stack
4)Runtime Stack
5)Machine Stack

Reference:@akshaymarch7

Top comments (0)