Skip to content
Async JavaScriptChapter 32 / 47Intermediate4 min read

Callbacks

Learn what JavaScript callbacks are, the difference between sync and async callbacks, the error-first pattern, and how to avoid callback hell.

On this page

1. What are callbacks?

In JavaScript, functions are values, so they can be passed around like variables. When you say "run this function once the job is done", that function is a callback.

There are two kinds of callbacks: sync (run immediately, like map) and async (run later, like setTimeout or a click handler).

2. Why does it matter?

Callbacks let you make a function flexible. The function does not know what to do after the work, and the caller decides that.

Without callbacksWith callbacks
Write a separate function for every taskOne function, the caller supplies the behavior
Hard to wait for an async resultThe callback runs when the work finishes
Handling events is not possibleRun your own function on a click
Code is repeatedReusable higher-order functions

3. Where is it used?

PlaceExample
Array methodsarr.map((x) => x * 2)
Eventsbutton.addEventListener("click", handleClick)
TimerssetTimeout(showToast, 2000)
Node.js APIsfs.readFile(path, (err, data) => ...)
LibrariesHooks, plugins, custom sort compare functions

4. How does it work?

Async callback flow
You give the function a callback
The function starts its work
The work runs in the background
The work finishes, and the callback is called with the result

5. Code example

Your own higher-order function

js
function repeat(times, callback) {
  for (let i = 1; i <= times; i++) {
    callback(i);
  }
}

repeat(3, (n) => console.log(`Round ${n}`));

The error-first callback pattern

js
function loadUser(id, callback) {
  setTimeout(() => {
    if (id <= 0) {
      callback(new Error("Invalid id"));
      return;
    }
    callback(null, { id, name: "Ali" });
  }, 500);
}

loadUser(1, (error, user) => {
  if (error) {
    console.error(error.message);
    return;
  }
  console.log(user.name);
});

What callback hell looks like

js
loadUser(1, (err, user) => {
  loadOrders(user.id, (err, orders) => {
    loadInvoice(orders[0].id, (err, invoice) => {
      console.log(invoice);
    });
  });
});

How does the code work?

LineWhat is happening
repeat(3, ...)A sync callback, runs immediately inside the loop
callback(new Error(...))The first argument is the error, a Node.js style convention
callback(null, user)The error is null, the second argument is the data
if (error) returnCheck the error first, then use the data
Nested callbacksEvery step goes deeper, which is called callback hell

Interview tip

The fix for callback hell: Promises and Async / Await. These days, newer APIs return promises instead of taking callbacks, like fetch and fs/promises.

6. Common mistakes

Mistake: Calling the callback instead of passing it

Why? In doTask(done()), done runs immediately and its result is passed.

Better: Pass the reference: doTask(done).

Mistake: Ignoring the error argument

Why? When an error happens, the data is undefined and the code crashes later.

Better: In every error-first callback, check if (error) first.

Mistake: Calling the callback twice

Why? If you forget return after the error, the success callback runs as well.

Better: Return right after calling the callback with an error.

Mistake: Treating deep nesting as normal

Why? In callback hell, the code is hard to read, handle errors in, and test.

Better: Use promises and async await for async work.

7. What to learn before and after

Suggested order
Functions
Higher-Order Functions
Callbacks
Promises
Async Await

Final quick revision

PointDetail
CallbackA function passed as an argument
Sync callbackRuns immediately, like map
Async callbackRuns later, like timers and events
Error-firstThe (error, data) signature
Callback hellDeep nesting, solved with promises