# The event loop

**What is its purpose?**

It schedules callbacks to be able to be executed.

**Topics involved**

* The *call stack*: When a function is executed (synchronous code or callbacks), it enters the call stack. The *call stack* contains all the current executing functions, starting for the root (anonymous).
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739975531274/1f4bb04e-d4c1-4b25-8725-83d6b8ad102a.png align="center")
    
    ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739975451658/ffbcbcf1-2f62-418c-a862-95003c156009.png align="center")
    
* The *task queue*: Its a queue where asynchronous tasks are queued when they are completed.
    
* The *microtask queue*: It’s a queue where asynchronous microtasks are queued when they are completed.
    

**How *event loop* works?**

The *event loop* checks continuosly the *call stack.* If it is empty, it will check if any microtask is in the *microtasks queue*. If any, it will execute the callback and as soon as executed, it will enter the *call stack*. Then, it will check the *task queue* and if there is any task, it will execute the callback and as and as soon as executed, it will enter the *call stack*. This is a process that happens continuously as the name suggests.

**Small diagram**

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1739978366089/26393d96-1311-4878-a87d-08b73d5ffbdb.png align="center")

**Small example**

```javascript
// Synchronous code
console.log(1);

// Microtask
Promise.resolve().then(() => {
  console.log(2);
});

console.log(3);

// Task
setTimeout(() => {
  console.log(4);
}, 0);

Promise.resolve().then(() => {
  console.log(5);
});

console.log(6);
```

**Example output**

1  
3  
6  
2  
5  
4
