What the heck Event loop is

Call stack, Memory heap, web API's, Job Queue, Call back queue

Vrushabh Bayas
3 min readJul 15, 2021

Hello, every one I hope you all are doing good. As you can see in the title today’s topic is all about Stack, memory heap, and Event loop in JavaScript.

So Call Stack is a LIFO(Last In First Out ) data structure which is one of the components from the event loop. It’s the place where all the function call sits with all local data from the function. Function invocation creates the execution context of that function.

Memory heap is another component of the event loop where all the global data(variables and functions ) sits. See the below image for clarification.

Event loop components by Andrei Neagoie

When we run some JavaScript code in the browser the JavaScript engine (V8 in the Case of Chrome browser) parses that code and that code gets executed line by line and popped on and off the call stack.

Everything is fine until now but wait what about the web APIs (like set timeout). Web APIs are not something JavaScript recognizes. So in this case parser knows to pass it off to the Browser for it to handle. When the browser has finished running its method(In this case set timeout). It puts what is needed to be run by the JavaScript into the call back queue which is one of the component of the event loop.

The call-back queue can not be run until the call stack is empty because the call stack has a higher priority than the call-back queue.

So the event loop is constantly checking the call stack to see if it’s empty and if it’s empty it will go to the call back queue to add things back to the call stack i.e invoking the call back functions from the call-back queue

and once it’s back in the call stack it ran and then popped out of the call stack. In this example, the callback function of the set timeout will sit in the call-back queue.

In Es6 Promises has been introduced go through the below code snippet to understand the new component of event loop that’s Job Queue

The job queue is a similar data structure as call back queue only difference is that it has higher priority than the call back queue

See the above image in which the first console log is global after that console log from the promise.resolve gets printed this is due to Job queue component of the event loop. After that Browser finishes running the JavaScript due to this we see the undefined is the console. lastly, console.log from the set timeout got printed.

event loop → checks for the Call Stack →if it’s empty → checks for the job queue/priority queue → if it’s empty → checks for the callback queue

This is the link if you want to see how the event loop works this link contains a visual representation of how the event loop works.

--

--

Vrushabh Bayas

Software engineeer @joshSoftware Pvt Ltd. love to explore new things and teach them to as many people as possible.