Before we learn about the event loop. I want to talk about javascript first to understand event loop better.
Javascript is interpreted programming language meaning the source code is not compiled until the time of execution. But how does a machine understands the non-compiled code? Well, that is taken care of by javascript engine which is responsible for compiling the javascript code to machine code.

Call stack in javascript can do one only thing at time. Call stack is simple stack (LIFO) based data structure which executes by pushing code on top of the stack and popping it off from the top once execution is done.
function foo() {
console.log('foo');
}
function baz() {
foo();
console.log('baz');
}
console.log('outside');
baz();
// 1. print outside
// 2. print foo
// 3. print baz
console.log('outside') to top of the stack and execute and pop it off.baz() function call to top of the stack and execute it.foo() function call to top of the stack and execute it.console.log("foo") to top of the stack and execute it and pop it off.foo() function from the stack.console.log("baz") to top of the stack and execute and pop it off.baz() function from the stack.The event loop's job is quite simple, constantly check if the call stack is empty or not. If empty then pull the callback from the callback queue and put it on top the stack for execution.
Callback queue is a simple queue-based data structure (FIFO). This is where all asynchronous code is pushed to. From here event loop will take over and push the queued callbacks to call stack.
Callback queue is the reason that I/O events are non-blocking.
Web API's also known as Browser Object Model (BOM) is the API's that allows javascript to talk to web browsers.
Let us see an example of how web API works in the event loop. If you are a javascript developer I am sure you would have used setTimeout or setInterval.
function foo() {
setTimeout(function () {
console.log('foo');
}, 2000);
}
foo();
foo() to top of the stack and execute it.setTimeout() with callback to top of the stack and execute it and pop it off.Timer will be keeping track and executed inside the browser.callback to callback queue.callback from queue and add to the top of stack.console.log() to stack and execute it and pop it off.foo() from the stack.I hope in this post you have learned a little bit more about javascript and its runtime. The examples I showed are more of an abstract idea of the event loop and browser vendors would have implemented the event loop with a lot of optimizations but you get the idea right how it works. For the sake of this post I have skipped writing about micro tasks in event loop. For more read here.
I want to thank Philip Roberts for creating loupe an awesome tool to visualize how event loops work.
Thanks for reading it so far. See ya in the next post.