In this episode, we explore Callbacks in JavaScript—one of the fundamental concepts behind asynchronous programming. While callbacks provide powerful tools to manage async tasks, they also introduce potential issues like Callback Hell and Inversion of Control.
A callback function is a function passed into another function as an argument to be executed later.
console.log("Namaste");
setTimeout(function () {
console.log("JavaScript");
}, 5000);
console.log("Season 2");Output:
Namaste
Season 2
JavaScript
Here,
setTimeoutdelays the callback execution and demonstrates how async behavior works in JavaScript using callbacks.
const cart = ["shoes", "pants", "kurta"];api.createOrder(cart, function () {
api.proceedToPayment(function () {
api.showOrderSummary(function () {
api.updateWallet();
});
});
});- Difficult to read.
- Hard to maintain.
- Nested structure causes mental overhead and bugs.
When you pass a function as a callback, you're handing control to the parent function, trusting it to:
- Call the callback correctly.
- Call it only once.
- Handle errors properly.
This leads to loss of control over execution flow.
api.createOrder(cart, function () {
api.proceedToPayment(); // We trust createOrder to invoke this
});What if createOrder:
- Never calls the callback?
- Calls it multiple times?
- Crashes before calling it?
This risk is called Inversion of Control.
- JavaScript is single-threaded and synchronous by default.
- Callbacks help us write asynchronous code.
- Callback Hell is a downside of using nested callbacks.
- Inversion of Control means giving responsibility of calling the function to another function—which might be risky.
-
What is a callback function in JavaScript?
A function passed into another function to be invoked later.
-
What is Callback Hell?
A situation where callbacks are nested within callbacks, making the code hard to read and maintain.
-
What is Inversion of Control in JavaScript?
A loss of control when we rely on external functions to invoke our callback correctly.
-
Can you give a real-life example of callback hell?
API chains like:
createOrder → proceedToPayment → showSummary → updateWalletall dependent on the previous step. -
Why do we say async programming in JavaScript exists because callbacks exist?
Because JavaScript is synchronous by design, callbacks enable asynchronous behavior.