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
(n) => { ... }is a function passed toforEachas an argument. That function is the callback.forEachis the one that calls that callback, once for each item in the array. On each call,nholds the item being processed.doneis printed only after every call of the callback has finished, becauseforEachwaits for its callback to finish.
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
operationis an ordinary parameter. The difference is that its value is a function.operation(a, b)calls that function. Without(),operationonly names the function and does not run it.- The value the callback returns (
x + y) becomes the result ofoperation(a, b). Thencalculatereturns that result. - The same
calculatecan add or multiply, depending on the callback it gets.
Arrays have built-in methods that take a callback (written cb below) and return a new array:
arr.map(cb)holds whatcbreturns for each item. For example,[1, 2, 3].map((x) => x * 10)gives[10, 20, 30].arr.filter(cb)holds only the items for whichcbgivestrue. For example,[1, 2, 3].filter((x) => x > 1)gives[2, 3].
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:
setTimeout(callback, ms)only stores the callback to be called later.msis the length of the delay in milliseconds.- The code below
setTimeoutruns right away without waiting, sodoneis printed first. - 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
- Writing
()when handing over a callback.numbers.forEach(print())runs the functionprintright away, then passes its result, not the function. Writenumbers.forEach(print). - Forgetting
returnin a callback with curly braces. An arrow function with curly braces returns a value only when it has areturn. So(x) => { x * 2 }givesundefined. Write(x) => x * 2or(x) => { return x * 2; }. - Printing instead of returning. If a function only prints its result with
console.logand has noreturn, the code that called it getsundefined.
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.