Callback Hell

Ajinkya Jadhav
2 min readAug 28, 2022

--

JavaScript is a single-threaded synchronous language. But many times we have operations that may be asynchronous. Asynchronous operations in JavaScript can be achieved through callbacks.

What is a Callback function?

The callback is a function that we can pass as an argument in a higher-order function, it is the responsibility higher-order function to invoke the callback function.

Now let us understand callback function with the help of an example:

callback example

In the above example, takeUserName function has a dual task. firstly it accepts greeting as an argument, next it takes value from the user, and later invokes the greeting function.

This is the way a callback works, now let us see the flaw with this callback function.

Callback Hell

Callback Hell is a chain of nested callbacks logged up above one another forming a stockpile.

Note : above code is only for understanding purpose
Note: above code is only for understanding purpose

In the above code, fetchData() function takes API as a parameter and fetches data from API, and invokes sortData() function, which in turn, sorts our data and invokes filterData() function.

This can do the job, but, it creates a pile of callbacks, which is very hard to maintain and read. This is a tedious task for the developer. Hence, for solving this problem we can introduce “promises”.

I will make a blog diving into promises later.

--

--