You probably already know that JavaScript is a single-threaded language as you read this blog. However, JavaScript can carry out asynchronous actions that may appear to be occurring in parallel. JavaScript accomplishes this with the assistance of something known as an Event Loop. Let's dive into how an Event Loop operates in this blog.
There are 4 main things to be seen when a Javascript engine is running.
The CallStack
Webapis/Libuv
Event Queue
Event Loop
CallStack is literally a stack(LIFO) which tracks what part of the program is running. When a function is called, it gets pushed to the Callstack and when the function returns, it gets popped from the Callstack.
WebAPIs are built-in browser APIs that enables asynchronous operations in JavaScript(in browser) whereas Libuv is a cross-platform library that provides support for asynchronous operations in Node.js. When there is an asynchronous call (like an API call or a DB Query) in our program, it gets handed over to WebAPi/Libuv. While WebAPi/Libuv are handling the queries, Javascript is not blocked and can continue executing the program further.
Event Queue is a queue(FIFO) where callbacks for these asynchronous calls are pushed once they are processed. So when WebAPi/Libuv are done handling the asynchronous calls, the corresponding callbacks are pushed into the Event Queue.
Event Loop is the one which connects the Event Queue with the Callstack. Its sole purpose is to check if the Callstack is empty and push the first item from the Event Queue to the Callstack. So when the Callstack is empty, the callback for an asynchronous event that was called earlier gets executed.
This is how Javascript handles async calls being a single-threaded language. Now you know WTF is an event loop in Javascript !
I was heavily inspired by the blog post(https://dev.to/nodedoctors/an-animated-guide-to-nodejs-event-loop-3g62) about how Nodejs event loop works while writing this blog. Thanks for giving it a read!