Callback hell 🔥 in Javascript and how to avoid it — JS Interview series

Shaik Wasef
JavaScript in Plain English
2 min readJan 8, 2023

--

Callback hells are one of the most common JS questions as far as full-stack and front-end interviews are concerned. In this article, we shall learn about what are callback hells and how one can avoid them during development. So let’s get started

What is a callback?

A callback is a function that is passed to another function as an argument. Callback functions are generally used in order to handle asynchronous programming in JS i.e In case you want to execute a certain function post the execution of a certain task or action (which consumes time ex. API call ).
Before going through the following example please read about setTimeout. Consider the following examples from Figure 1. :

Figure 1.

We originally wanted to execute the functions f1, f2, and f3 in order. Hence, we had to use multiple setTimeouts with different times ( observe the waiting time in each setTimeout ).
The output of the above program is

Imagine how difficult it would have been to understand the outcome of the above code if there were more than 3 set timeout functions. This is an example of a typical callback hell. Callback Hell is essentially nested callbacks stacked below one another forming a pyramid structure. Every callback depends on/waits for the previous callback, thereby making a pyramid structure that affects the readability and maintainability of the code.

How to solve the problem of callback hell?

  1. Divide your code into reusable functions :
    Dividing the code into reusable functions can help since this promotes code readability.
Figure 2

The output of the above code is the same as that from Figure 1. However, the code is much more organized. Observe that the functions have been moved to the bottom of the code since JS supports generic function hoisting.

2. Modularize code —
Declaring and exporting your function to other relevant files helps and provides more readability. module.exports() in Node.js can be used to export a function.

3. Handle Errors —
Handling errors if any help to identify which function is causing a possible error in execution.

Figure 3.

The above code shows an example of introducing an error message for fs.readFile() .

Thank you for reading this article. Kindly post any questions in the comments section.

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter, LinkedIn, YouTube, and Discord.

Interested in scaling your software startup? Check out Circuit.

--

--