Callback Hell in JavaScript
JavaScript is an asynchronous (non-blocking) and single-threaded programming language, meaning only one process can be run at a time.
In programming languages, callback hell generally refers to an ineffective way of writing code with asynchronous calls. It is also known as the Pyramid of Doom.
The callback hell in JavaScript is referred to as a situation where an excessive amount of nested callback functions are being executed. It reduces code readability and maintenance. The callback hell situation typically occurs when dealing with asynchronous request operations, such as making multiple API requests or handling events with complex dependencies.
To better understand the callback hell in JavaScript, first understand the callbacks and event loops in JavaScript.
Callbacks in JavaScript
JavaScript considers everything as an object, such as strings, arrays, and functions. Hence, the callback concept allows us to pass the function as an argument to another function. The callback function will complete the execution first, and the parent function will be executed later.
The callback functions are executed asynchronously and allow code to continue running without waiting to complete the asynchronous task. When multiple asynchronous tasks are combined, and each task depends on its previous task, the code structure becomes complicated.
Let's understand the use and importance of the callbacks. Let's assume an example we have a function that takes three parameters one string and two numbers. We want some output based on the string text with multiple conditions.
Consider the below example:
function expectedResult(action, x, y){ if(action === "add"){ return x+y }else if(action === "subtract"){ return x-y } } console.log(expectedResult("add",20,10)) console.log(expectedResult("subtract",30,10))
Output:
3020
The above code will work fine, but we need to add more tasks to make the code scalable. The number of conditional statements will also keep increasing, which will lead to a messy code structure that needs to be optimized and readable.