All 28 lessons ▾

Inside JavaScript · Lesson 20 of 28

Callback Hell and Inversion of Control

Updated 11 Nov 2026 · By Akshay, software engineer, India · 8 min read

So callbacks made async JavaScript possible. But they have a dark side: a pyramid of doom, and handing your code to strangers. So let's see both.

The video for this lesson is coming soon.

A new lesson goes up every day at 11 am. Subscribe on YouTube so you don't miss it.

Got a doubt? Ask in the comments under the video.Subscribe

In one minute
  • Callbacks make async JavaScript possible
  • Dependent steps nest: callback hell
  • Its shape: the pyramid of doom
  • Errors at every level make it worse
  • Inversion of control: someone else runs your code
  • Promises fix both

Part 1The good part

So we've used callbacks a lot in this course, and they're amazing. But today, we look at their dark side. Because understanding what's wrong with callbacks is the best way to understand promises, which come next. So first, a quick reminder of the good part.

good.js
1console.log("Inside");2setTimeout(function () {3  console.log("JavaScript");4}, 2000);5console.log("rocks!");
Output
Inside
rocks!
JavaScript

So JavaScript is synchronous and single threaded. Give it three lines, and it runs them one after another, without waiting. But what if we want one line to happen later? A callback! Line one prints Inside. Line two hands a function to setTimeout, for two seconds. Line five prints rocks. And two seconds later, the callback prints JavaScript. So without callbacks, there would be no way to say, do this later. That's the good part. Async JavaScript exists because callbacks exist.

Part 2When steps depend on each other

Now let's build something real. Booking a movie ticket. And watch carefully what happens to our code. Almost every app you use works in steps like this, one waiting for the other.

booking.js
1const seats = ["A1", "A2"];2 3api.bookSeats(seats);4api.makePayment();

So booking a movie ticket takes steps. First, book the seats, A1 and A2. Then, make the payment. But there's a catch. Booking talks to a server, so it takes time. And payment must only happen after the seats are booked. Now we can't just write the two lines one after the other, because JavaScript won't wait for bookSeats to finish. So how do we say, pay only after booking is done?

callback-step.js
1api.bookSeats(seats, function () {2  api.makePayment();3});

With a callback! So we pass the payment step as a function into bookSeats. Now bookSeats books the seats, and when it's done, it calls our function, which makes the payment. The dependency is handled. Nice and simple. But wait. After payment, we need to send the ticket. And after the ticket, add reward points. So now what?

pyramid.js
1api.bookSeats(seats, function () {2  api.makePayment(function () {3    api.sendTicket(function () {4      api.addRewards(function () {5        console.log("All done!");6      });7    });8  });9});

So each step goes inside the callback of the step before it. Payment inside booking. Ticket inside payment. Rewards inside ticket. Now look at the shape of this code. It keeps growing sideways, to the right. Every new step pushes it further. So this is called callback hell. And because of its shape, people also call it the pyramid of doom. Scary name.

real-pyramid.js
1api.bookSeats(seats, function (err, booking) {2  if (err) return showError(err);3  api.makePayment(booking, function (err, payment) {4    if (err) return showError(err);5    api.sendTicket(payment, function (err, ticket) {6      if (err) return showError(err);7      api.addRewards(ticket, function (err) {8        if (err) return showError(err);9        console.log("All done!");10      });11    });12  });13});

And now real code is even worse. Each step can fail. The network can drop, the card can be declined. So in real projects, every callback gets an error first, and checks it. If there's an error, show it and stop. Now look at it. Four steps, four error checks, and the actual logic is buried deep inside. Imagine ten steps. Hard to read, hard to change, and very easy to break. So that's why callback hell is a real problem, not just an ugly shape.

REMEMBER THIS
Callbackhell:callbacks
nestedinsidecallbacks,
growingsideways.
also called the pyramid of doom

So remember this. Callback hell is when callbacks are nested inside callbacks, inside callbacks, because each step depends on the one before. The code grows sideways instead of down. It's hard to read, hard to maintain, and handling errors at every level makes it worse. So that's problem number one.

named-steps.js
1function onBooked(booking) {2  api.makePayment(booking, onPaid);3}4function onPaid(payment) {5  api.sendTicket(payment, onTicket);6}7function onTicket(ticket) {8  api.addRewards(ticket, onDone);9}10function onDone() {11  console.log("All done!");12}13 14api.bookSeats(seats, onBooked);

Now, can we escape the pyramid without anything new? Partly, yes. So give every step a name. onBooked makes the payment, and passes onPaid. onPaid sends the ticket, and passes onTicket. And so on. Each function sits at the left edge, so the code reads top to bottom, like a list of steps. That's much better to read. But now notice, we're still handing every one of these functions to someone else's code. So the shape is fixed. The trust problem is not.

Part 3Inversion of control

And now, problem number two. It's less visible, but much more dangerous. It's called inversion of control.

trust.js
1api.bookSeats(seats, function () {2  api.makePayment();3});

So look at this simple code again. We wrote the payment step. It's our most important code, because it takes the user's money. But who calls it? Not us! We handed it to bookSeats, and now we're blindly trusting bookSeats to call it. Maybe bookSeats was written by another team, or a third-party company. We can't see inside it. We just hope it calls our function, at the right time, exactly once. So it's like giving your house keys to a stranger, and asking them to water your plants. Maybe they will. Maybe they'll forget. Maybe they'll come in twice a day. You just don't know.

Your callback
makePayment
bookSeats
someone else's
code
Never called
the user is
stuck
Called twice
charged twice!
Called too
early
before the
booking
handed
over
REMEMBER THIS
Inversionofcontrol:you
giveyourcodeaway,and
losecontrolofwhen,and
howoften,itruns.
you can only hope they call it right

So when you give your callback to someone else's code, you hand over control. And many things can go wrong. What if it's never called? The user waits forever. What if it's called twice? The user is charged twice! What if it's called too early, before the seats are even booked? Or with the wrong data? So you can't control any of it. That's inversion of control.

So remember this. Inversion of control means you lose control of your own code, when you pass it as a callback. You're trusting another function to call it at the right time, the right number of times, with the right data. Now normally, you control your program. With callbacks, that control is inverted. It goes to someone else. And if you want to read more, this idea is explained beautifully in Kyle Simpson's book series, You Don't Know JS.

guard.js
1let paid = false;2 3api.bookSeats(seats, function () {4  if (paid) return;5  paid = true;6  api.makePayment();7});

Now can we protect ourselves? A little. So here, we keep a flag called paid. The first time our callback runs, paid is false, so we set it to true, and make the payment. If bookSeats calls us again by mistake, paid is already true, so we return straight away. No double charge. Every important callback now needs its own guard, and guards for never, and for too early, and for errors too. That's a lot of defensive code, just to trust someone. So promises give us these guarantees for free.

Part 4The way out

So, is there a better way? Yes! And it's coming in the very next episode.

COMING NEXT
Promises:insteadof
givingawayyourcallback,
yougetapromise,and
attachityourself.
flat code, and the control stays with you
INTERVIEW ANSWER
Callbackshavetwo
problems:callbackhelland
inversionofcontrol.
promises were made to solve both

So promises fix both problems. Instead of handing your callback to bookSeats, bookSeats gives you back an object, a promise, that says, I'll let you know when I'm done. And you attach your next step to it yourself. Your function stays in your hands, and a promise settles only once, so your step can't run twice. And promises can be chained, one after another, so the code goes down, not sideways. No more pyramid. So we'll see exactly how, next time.

Quick quiz
quiz.js
1payWith(card, function (receipt) {2  emailReceipt(receipt, function () {3    updatePoints(function () {4      console.log("all done");5    });6  });7});

Can you spot two problems in this code?

Show the answer

So problem one. It's nested three levels deep, and every new step will push it further right. That's callback hell. Problem two. We're trusting payWith to call our function correctly, and only once. If payWith has a bug and calls it twice, the email goes out twice, and the points are added twice. So control was never ours. Did you spot both?

Homework

In the comments, explain these two problems in your own words. Writing it yourself is the best way to remember it.

Show the answer

Problem one, callback hell. Each step needs the result of the one before, so each callback goes inside the previous one. The code grows sideways into a pyramid, and it gets hard to read, to change, and to handle errors in.

Problem two, inversion of control. When we pass our function to payWith, we hand control to someone else's code. We're trusting it to call our function, only once, at the right time, with the right data. If that code has a bug, our code pays for it.

Promises fix both: steps become a flat chain instead of a pyramid, and we keep control, because we attach our function to the promise ourselves.

Try it first, then post yours in the comments under the video.

Your progress stays on this device.
A new lesson every day at 11 am

The video on YouTube, and the lesson as a swipe-through on Instagram.