"When you're done with your current work, call me back."
What are Callbacks in JavaScript?
A callback is a function that is passed as an argument to another function and is executed later, usually after a task or operation has completed.
They allow JavaScript to continue executing other code instead of waiting for the operation to complete.
Why Are Callbacks Needed?
Callbacks are widely used in JavaScript. for handling asynchronous operations. When an asynchronous task finishes, the Event Loop executes the corresponding callback, enabling non-blocking behavior.
For example:
function orderPizza(callback) {
console.log("Preparing pizza...");
callback();
}
orderPizza(() => {
console.log("Pizza is ready!");
});
// Output:
// Preparing pizza...
// index.js:7 Pizza is ready!
Problems with Callbacks approach
- Deep nesting (callback hell).
- Repeated error handling.
- Harder to read and maintain.
- Difficult to coordinate multiple async operations.
What is callback hell?
Is it an error?
callback hell is not an error,Callback hell is a coding pattern where many nested callbacks make code.
- The code becomes hard to read.
- Error handling becomes messy.
- Debugging and maintenance become difficult.
It's also called the Pyramid of Doom because the indentation keeps increasing.
For example:
getUser(function(user) {
getOrders(user.id, function(orders) {
getProducts(orders, function(products) {
getShippingDetails(products, function(details) {
console.log(details);
});
});
});
});
How do we avoid callback hell?
Callback hell is avoided by writing asynchronous code in a way that is easier to read and maintain. The most common approaches are:
Using Promises Or, even better, using async/await
Callbacks were the original mechanism for handling asynchronous operations in JavaScript.