DEV Community

Cover image for Summarizing Namaste πŸ™ JavaScript EP02 (How Js code is executed and Call stack)
Abhinav Singh Jamwal
Abhinav Singh Jamwal

Posted on

Summarizing Namaste πŸ™ JavaScript EP02 (How Js code is executed and Call stack)

Thank you Akshay Saini for this beautiful series. Just summarizing your lessons for whenever I need a quick recap. Same for others. Hope it helps.

Execution context is created in two phases:

1-> Memory creation or allocation phase
2-> Code execution phase

Now first see memory creation phase.

image

In above image, there is a simple js code and a rough diagram of execution context parts.
Js will allocate memory to all the variables and functions.

Note: All variables in first phase are assigned a value of undefined

When js encounters var n, it allocates n a memory with a value undefined.
Similar happens to square2 and square4.
In case of function, a key named square is allocated in memory with a value (whole square function code {...}).
image

Now see Code execution phase.
Js once again runs line by line and executes the code.
At line 1, it assigns the actual value(2) instead of undefined which was assigned in phase 1.
At line 2, it doesnt find anything to execute and goes to line 6.
At line 6, function is invoked.
Think of function like a mini program.So, when a mini program aka function is invoked, a whole new execution context is created.

image

Since, new execution context is created. Memory and code execution phases are repeated.

Memory phase
image

Code execution phase
First it will assign num with value 2.
Then, first line of function is executed and the result which is 4 is assigned to ans.

return states that return the value to the place it was invoked or return back to the origin from where it was invoked.
So, second line of function is executed and the execution is back to its origin.

image

The function execution context is deleted after completion
Same thing happens at line 7 and its execution context is also destroyed after completion.
image

After doing all executions, global execution context is also destroyed after completion.

How does Js manages these execution context if there are alot of functions inside function or else case?

Answer is Call Stack
Js has its own call stack. Call stack maintains the order of execution of execution contexts.

image

GEC-> Global execution context
E1-> First execution context

After completion E1 is destroyed. Then E2 is pushed and is destroyed after completion.
At last after all executions, GEC is also deleted.

Top comments (0)