The Event Loop in JavaScript

Call Stack:

The call stack is a stack that holds the calls in the LIFO queue (Last In, First Out).

A Simple Example:

In this example, we have three functions called country, state, and city.

const city = () => console.log("city");const state = () => console.log("state");
const country = () => { console.log("country"); state(); city();}country();
countrystatecity

The Message Queue:

Now let's see how the call stack will look if we use setTimeout:

const city = () => console.log("city");const state = () => console.log("state");
const country = () => { console.log("country"); setTimeout(state,0); city();}
country();
countrycitystate

The Job Queue (ES6):

Apart from Message Queue, there is another concept in ES6 called Job Queue which is used by Promises. It executes the result of an asynchronous function as soon as possible instead of putting them at the end of the call stack.

const city = () => console.log("city");const state = () => console.log("state");
const country = () => { console.log("country"); setTimeout(state,0); new Promise((resolve, reject) => resolve("After city and before state") ).then(resolve => console.log(resolve)); city();}country();
countrycityAfter city and before statestate

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store