TExcelTAD
Home › JavaScript › JS Callbacks

JavaScript Callbacks

A callback is a function you pass to another function, so that the other function can call it ("call it back") later. You've already used callbacks with array methods like map and filter. They're also the original way JavaScript handles asynchronous work — things that finish later, like timers, user clicks or network requests.

Functions as arguments

Because functions are values, you can hand one to another function, which decides when (and how often) to call it:

js · try it yourself
function repeat(times, action) {
  for (let i = 1; i <= times; i++) {
    action(i);
  }
}

repeat(3, (n) => console.log("Hello #" + n));

function calculate(a, b, operation) {
  return operation(a, b);
}
console.log(calculate(6, 3, (x, y) => x + y));
console.log(calculate(6, 3, (x, y) => x * y));
console.log(calculate(6, 3, Math.max));
Hello #1
Hello #2
Hello #3
9
18
6

These are synchronous callbacks — they run immediately, during the outer function's execution. Array methods (forEach, map, sort…) work this way.

Asynchronous callbacks

Some callbacks run later, after the current code has finished. setTimeout(callback, ms) is the simplest example: it schedules the callback and returns immediately.

js · try it yourself
console.log("1. ordering coffee");

setTimeout(() => {
  console.log("3. coffee is ready ☕");
}, 300);

console.log("2. reading the news while waiting");
1. ordering coffee
2. reading the news while waiting
3. coffee is ready ☕

JavaScript doesn't stop and wait at setTimeout. It keeps running the rest of the code, and when the timer expires, the callback is run. This non-blocking style lets a single-threaded language stay responsive.

Event handlers are asynchronous callbacks too — the browser calls them whenever the event happens:

js
button.addEventListener("click", () => {
  console.log("clicked!");   // runs later, possibly many times
});

Error-first callbacks

Since an asynchronous function can't simply return its result or throw to the caller (the caller has already moved on), the classic Node.js convention is to pass an error as the first argument of the callback, and the result as the second:

js · try it yourself
function loadUser(id, callback) {
  setTimeout(() => {
    if (id <= 0) {
      callback(new Error(`Invalid id ${id}`));
    } else {
      callback(null, { id, name: "User " + id });
    }
  }, 50);
}

loadUser(7, (err, user) => {
  if (err) return console.log("Failed:", err.message);
  console.log("Loaded:", user);
});

loadUser(-1, (err, user) => {
  if (err) return console.log("Failed:", err.message);
  console.log("Loaded:", user);
});
Loaded: { id: 7, name: 'User 7' }
Failed: Invalid id -1

Callback hell

When one asynchronous step depends on the previous one, callbacks get nested inside callbacks. The code drifts to the right and error handling repeats at every level — the infamous "pyramid of doom":

js · try it yourself
function step(name, ms, callback) {
  setTimeout(() => callback(null, name), ms);
}

step("login", 30, (err, a) => {
  if (err) return console.log(err.message);
  console.log("done:", a);
  step("load profile", 30, (err, b) => {
    if (err) return console.log(err.message);
    console.log("done:", b);
    step("load orders", 30, (err, c) => {
      if (err) return console.log(err.message);
      console.log("done:", c);
      console.log("all steps finished");
    });
  });
});
done: login
done: load profile
done: load orders
all steps finished

It works, but it's hard to read, hard to change, and easy to get wrong. Promises and async/await (the next two chapters) were invented to solve exactly this problem: the same sequence becomes flat, readable code.

Callbacks today

Callbacks are still everywhere — they're just not the preferred way to handle "one result, later" anymore:

Use case Callbacks still the norm?
Array methods (map, filter, sort) ✅ yes (synchronous)
Event listeners ✅ yes (may fire many times)
Timers (setTimeout, setInterval) ✅ yes
One-time async results (network, files) ❌ use promises / async-await

Tip: When writing your own callback-taking function, document clearly whether the callback runs synchronously or later — mixing both in one function causes subtle bugs.

Test yourself

What is a callback?

  1. A function that calls itself
  2. A function passed to another function to be called by it
  3. A function that returns a function
  4. A built-in browser API

What is printed first? setTimeout(() => console.log("A"), 0); console.log("B");

  1. A
  2. B
  3. They print at the same time
  4. Nothing

In an error-first callback (err, data) => {…}, what is err on success?

  1. undefined or null
  2. An Error
  3. The data
  4. false