Callbacks — JavaScript

A callback is a function passed to another function as an argument, and the function that receives it is the one that calls it. Examples of such functions are…

At a food stall, you order a stuffed pancake and tell the cook: "Call me when it's ready." You don't stand by the pan and wait. You sit down and look at your phone. When the pancake is ready, the cook calls you.

In JavaScript, that "call me" message is called a callback. A callback is a function you pass to another function as an argument. The function that receives it is the one that calls it later, the way the cook calls you. You have already used callbacks: the small functions inside map, filter and addEventListener are all callbacks.

A function passed to another function

The code below passes a function to forEach:

console.log("start");

const numbers = [1, 2, 3];
numbers.forEach((n) => {
  console.log("callback:", n);
});

console.log("done");

What is printed:

start
callback: 1
callback: 2
callback: 3
done

In short, you pass the callback, and the function that receives it calls it.

Write a function that takes a callback

A function you write yourself can take a callback too. calculate below takes two numbers and one function:

function calculate(a, b, operation) {
  return operation(a, b);
}

console.log(calculate(6, 3, (x, y) => x + y)); // 9
console.log(calculate(6, 3, (x, y) => x * y)); // 18

Arrays have built-in methods that take a callback (written cb below) and return a new array:

A callback that is called later

A callback is not always called right away. setTimeout calls its callback after a delay:

console.log("start");

setTimeout(() => {
  console.log("1 second later");
}, 1000);

console.log("done");

What is printed: start, done, then 1 second later. The order is this:

  1. setTimeout(callback, ms) only stores the callback to be called later. ms is the length of the delay in milliseconds.
  2. The code below setTimeout runs right away without waiting, so done is printed first.
  3. After 1000 milliseconds (1 second), the callback is called.

addEventListener works the same way: its callback is called later, every time the event happens.

Callbacks inside callbacks

When several steps must run one after another, the callbacks nest deeper and deeper. Each callback is written inside the callback before it:

setTimeout(() => {
  console.log("step 1");
  setTimeout(() => {
    console.log("step 2");
    setTimeout(() => {
      console.log("step 3");
    }, 500);
  }, 500);
}, 500);

Each step starts only after the step before it has finished, so the code moves further and further to the right. This shape is nicknamed callback hell: it is hard to read, and it is hard to find mistakes in. With Promises and async/await, you can write the same steps flat, from top to bottom. Both are covered in later lessons.

⚠️ Callbacks that run too early, or return nothing

TL;DR: A callback is a function passed to another function as an argument, and the function that receives it is the one that calls it. Examples of such functions are forEach, map, filter, setTimeout and addEventListener. Pass the function without (). In a receiving function you write yourself, the callback arrives in a parameter (for example cb) and you call it with cb(). forEach calls its callback right away. setTimeout calls it later, while the rest of the code keeps running. Callbacks nested deeper and deeper are nicknamed callback hell, and Promises or async/await (covered later) make them tidy.

⚡ You pass it, it does the calling

Write:

function calculate(a, b, operation) {
  return operation(a, b);
}

calculate(6, 3, (x, y) => x + y); // 9
calculate(6, 3, (x, y) => x * y); // 18

Meaning: A callback is a function passed to another function as an argument, here (x, y) => x + y. The callback arrives in the parameter operation, and calculate is the one that calls it, with operation(a, b). The same calculate can add or multiply, depending on the callback it gets.

⚡ A callback that is called later

Write:

console.log("start");

setTimeout(() => {
  console.log("1 second later");
}, 1000);

console.log("done");
Guess first: setTimeout(callback, 1000) calls its callback 1000 milliseconds (1 second) later. In what order are the lines printed?

start, done, then 1 second later. setTimeout only stores the callback. The code below it runs right away without waiting.

Meaning: A callback is not always called right away. forEach calls its callback right away. setTimeout and addEventListener call it later.

⚡ Pass it without ()

Meaning: If numbers is an array and print is a function, numbers.forEach(print()) runs print right away, and what is passed to forEach is its result. Write numbers.forEach(print), so that forEach is the one that calls print.

What you will learn