JavaScript Call back hell explained in simple terms.
Callback hell in JavaScript refers to an ineffective way of writing code with asynchronous calls. It’s also humorously known as the Pyramid of Doom. Let me break it down for you:
Asynchronous Nature of JavaScript:
- JavaScript is asynchronous and single-threaded. This means that only one process can run at a time.
- When dealing with asynchronous tasks like making API requests or handling events, we often use callbacks to manage the flow of execution.
What Is Callback Hell?:
- Callback hell occurs when we have an excessive amount of nested callback functions.
- Imagine a situation where each asynchronous task depends on its previous task, leading to a tangled web of callbacks.
- This tangled structure reduces code readability and maintainability.
Example:
- Let’s say we have a function that performs different operations based on an action (e.g., “add” or “subtract”) and two numbers.
- Initially, our code might look like this:
JavaScript
function expectedResult(action, x, y) {
if (action === "add") {
return x + y;
} else if (action === "subtract") {
return x - y;
}
}
console.log(expectedResult("add", 20, 10)); // Output: 30
console.log(expectedResult("subtract", 30, 10)); // Output: 20However, as we add more tasks and conditions, the code becomes less readable.
Get anushkamahajan901’s stories in your inbox
Join Medium for free to get updates from this writer.
Avoiding Callback Hell:
- To improve readability, we can use separate functions for each operation (e.g.,
addandsubtract):
JavaScript
function add(x, y) {
return x + y;
}
function subtract(x, y) {
return x - y;
}
function expectedResult(callBack, x, y) {
return callBack(x, y);
}
console.log(expectedResult(add, 20, 10)); // Output: 30
console.log(expectedResult(subtract, 30, 10)); // Output: 20- By using separate function bodies and passing functions as callbacks, we improve code readability and maintainability.
Remember, callback hell is like a tangled web of callbacks — best avoided for the sake of our sanity!
Follow for more tech related contents :)




