In JavaScript, callbacks are functions passed as arguments to other functions and executed after a task completes. Callbacks are useful for handling asynchronous operations like reading files, making API requests, or working with timers.
However, when multiple asynchronous operations depend on each other, using too many nested callbacks makes the code difficult to read and maintain. This situation is known as Callback Hell.
What is Callback Hell?
Callback Hell happens when callbacks are nested inside other callbacks, creating deeply indented and confusing code.
It usually looks like a pyramid structure and becomes hard to debug or maintain.
Example of Callback Hell
// Nested callbacks
setTimeout(() => {
console.log("Step 1: User logged in");
setTimeout(() => {
console.log("Step 2: Fetch user data");
setTimeout(() => {
console.log("Step 3: Show user dashboard");
setTimeout(() => {
console.log("Step 4: Load user notifications");
}, 1000);
}, 1000);
}, 1000);
}, 1000);
OUTPUT
Step 1: User logged in
Step 2: Fetch user data
Step 3: Show user dashboard
Step 4: Load user notifications
Top comments (0)