What is Event loop in Javascript and what it does?

What is Javascript?

Let's clear this up first. Javascript is a programming language used to develop web apps. It is also used to develop cross-platform desktop and mobile applications (through frameworks).

JS is Single-Threaded, non-blocking, and supports asynchronous programming.

To know about Event-loop and its working we need to know about a few other things, i.e Call Stack and Task Queue.

What is Call Stack

To be short and concise :

  • The working of the call stack is the same as the stack data structure.

  • The stack data structure can be equated with a stack of plates.

  • The last item pushed gets popped (deleted) first

  • Heap is used for allocating memory.

  • Tasks are appended to call stack in a sequential manner and removed in the same fashion.

    let's see a simple example of the working of call stack:

      function answer(){
          say("Good Morning");
      }
      function say(text){
          console.log(text)
      }
      answer()
      //output : Good Morning
    

What is a Task-Queue?

  • Since Javascript is single-threaded, it can only do one task at a time; hence, in cases where multiple tasks need execution, they get pushed into the task queue.

  • The tasks in the task queue wait for their turn for execution.

  • This is where the Event Loop comes in, its job is to push the task from the task queue to the call stack.

This was a simple explanation of the basics of Event-loop. Its internal working is a different monster that can be covered another day. Feel free to post a comment.