Javascript Call Stack and Event loop

Javascript has been very popular programming languages since years and It is becoming the best version of it day by day. Well Javascript is very weird language if you don’t know how javascript programs executed.

Javascript is single threaded programming language. i.e. it can do one task at a time. It has provided only one call stack to run the code. Concurrency achieved in javascript by using asynchronous javascript callback, promise, async/await etc. We simply attach a callback to a function and when the function gets completed then callback is triggered.

Javascript is executed by some javascript engine: v8, spider monkey, chakra etc

Execution Context: Javascript programs are divided into multiple execution context. There are global execution context and function execution context. In every execution context two things happened

(hoisting + execution) — In hoisting every new variables has given memory space with value undefined, and function has given space where all it’s code sit. Every function creates a new execution context and these two things happened in each new execution context.

Components of Javascript engine

Call Stack: A stack is simply a data structure that stores the current state of the program. It simply tells where currently we are in the program. An items is added last get remove first (LIFO) when it is completed. When program step in function then it is pushed to the call stack when program return from the function then it is popped out from the stack.

Heap: Heap is memory storage where it stores the all the objects.

How does the Asynchronous javascript works?

Blocking: Blocking is simply some instruction wait for it’s previous instruction to be completed then only the next instruction will start executing. So let’s suppose we want to process some images and we have defined a function for that. This function will take some to get completed till then no instruction will be pushed to the call stack. When it is finished then next instruction will be pushed to the call stack. So basically Blocking blocks the call stacks to enter new instructions.

What’s the solution?

Even Loop:

Web browser’s provides a lot of web api(setTimeout, DOM events, fetch etc) In Node.js it is C++ API. Now simple solution is provide a callback function to image processing or any web api. So when browser see something that has asynchronous thing then it is popped out from the stack and wait for it to complete, When it is completed or triggered then the corresponding callback pushed into the message queue (Job queue). Now event loop’s job is to monitor the stack and message queue when stack is empty then event loop pop one item from queue and pushed to stack.

Message Queue: A data structure to store the messages to be processed later.

Promises has given more priority in message queue then callbacks.