WHAT IS JAVASCRIPT EVENT LOOPS AND CALLSTACK FOR BEGGINERS
Published: 2023-07-23 06:42:18

The Event Loop, one of the most important aspects of JavaScript and is also one of the most misunderstood. 

The posts aim is to explain how javascript, a single threaded language is able to run asynchronous and synchronous code simultaneously.

#### What do we mean javascript being a single threaded language


It simply means that javascript by default is only able to execute codes **one after the other**, from top to bottom, and must finish executing a piece of code before moving onto the next one. This is because it has one call stack.

this means that the code
```

console.log("this will run first")
console.log("this will run second, after first line")

```
The first line will write to the console before the second line. if you run this code a million times, it would always follow this order.


For most programmers both old and new, this is pretty much what we expect from our code. The problem comes when we have a line/block of code that takes sometime to complete; maybe we're getting data from a database to use or we just want to execute some code after a delay. 

For example

```
console.log("this is the first line of code")

setTimeout(function(){
console.log("this is the second line of code")
},4000)

console.log("this is the third line of code")
```

With the code we've written, we're saying write to the console the first line of code, then wait 4 seconds and write the second line, then write to the console the third line of code. Ideally with what we've explained you expect the first line to write and wait 4 seconds before writing the second line to the console, and only after that should the third line write to the console. 

but what if we didn't want the third line to wait, I mean if we wanted it to wait, we should have added it in the setTimeout block right? you can begin to see the problem it could cause if every time we have a code that takes some time to do, it blocks the remaining blocks the remaining code. in simple term it would be a bad experience for the users. this is where event loops comes in.

the output of the above code in the console would be 
```
console.log("this is the first line of code")
console.log("this is the third line of code")
// after 4 seconds
console.log("this is the second line of code")
``` 

So to briefly explain event loop, it is the mechanism that allows javascript perform non-blocking input and output operations. Now we could end like this, but it would be unfair to the call stack and the task queue for giving the event loop all the credit, it is an operation that they all play a part in making successful.


![How javascript call stack, event loops and task queue work](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqjk6643dbikp3j5mlyb.png)

#### What is the call stack ?

The call stack is used to keep track of where the JavaScript engine is in the code. When a function is called (being executed), it is added to the top of the call stack. When the function returns, it is removed from the call stack.

The call stack uses a system called LIFO which means the last in first out, the last function called in the call stack will leave first. in practice, say we have functions that call other functions

```
const a = function(){
    console.log("this is function a")
}
const b = function(){
    console.log("this is function b")
    a()
}
const c = function(){
    console.log("this is function c")
    b()
}

c()
```
as we can see from the code, c is called, then the function calls b which then calls a. by LIFO standards a being the last function called would be the last to enter the call stack but the first to leave followed by b and then c which was called first. 
To see the call stack in action copy and paste this code in between a script opening and closing tag in a html file and open in your browser. Open the developer tool in your browser using `ctrl + shift + i`, click on sources and open the html file, add a break point where we called the function c, reload the page and use the down arrow button to call the next line of code. this should be the stages of the function calls in your call-stack 


![The call stack in action](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kktnwm5wtphs7iz1qbyj.png)


So in simple terms, the call stack is a tool that tells us which part of our code is currently running. it also has other functions but for the scope of our topic, this is what it does.


### What is the Task Queue

The task queue is a list of messages (or tasks) that need to be processed. Each message is associated with a callback function. These messages usually represent the completion of asynchronous operations, like API requests, timers, or events.
Now we know our call stack is where functions that are being executed enters and leaves once done. when we have an asynchronous task/function ones it gets called in the call stack, it exists and runs in the background to prevent blocking other codes and ones the asynchronous task is completed it gets added to the Task Queue. The task queue can then be defined as a list of call back functions carrying responses from a completed asynchronous task. The task queue uses a method called FIFO; first in first out, the tasks that were first completed and added to the task queue will be executed first.

#### What is the Event Loop ?
The Event Loop is responsible for taking the callbacks from the task queue to the call stack for execution.
The Event Loop is a continuous loop that checks if there are completed tasks in the Task queue ready moved to the call stack for execution. When an asynchronous task gets completed and is added to the Task queue, the event loop is the mechanism that moves the functions/messages from the task queue into the call stack for execution and it only moves these functions from the task queue to the call stack when the call stack is empty (This means the event loop gives higher priority to the call stack).

#### To put all together
The javascript engine pushes synchronous task to the call stack for execution and asynchronous task are being handled in the background to prevent blocking, and when the asynchronous task is complete, it sends a call back into the task queue. the event loop moves the tasks from the task queue to the call stack only when it is empty (all synchronous codes in the call stack have finished executing).

so from our code example

```
console.log("this is the first line of code")

setTimeout(function(){
console.log("this is the second line of code")
},4000)

console.log("this is the third line of code")
```

The first console.log is executed immediately and added to the top of the call stack. The setTimeout function will be added to the call stack after that. Since setTimeout is an asynchronous function, it will leave the call stack and run in the background. After 4 seconds, the callback function is added to the task queue and moved back to the call stack for execution by the event loop.