A callback is a function you pass to another function, so that function can call it at the right time. The name comes from “call me back when you are ready”.
function greet(name, callback) {
console.log("Hello, " + name);
callback();
}
greet("Maya", function () {
console.log("Nice to meet you!");
});
Output: Hello, Maya, then Nice to meet you!. The greet function decides when the callback runs. You decide what it does.
You already use callbacks
Array methods take callbacks:
const prices = [10, 20, 30];
prices.forEach(price => console.log(price));
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // → [12, 24, 36]
So do events:
button.addEventListener("click", () => {
console.log("Clicked");
});
And timers:
setTimeout(() => console.log("Done waiting"), 500);
console.log("This prints first");
Passing a named function
A callback can be a function you defined earlier, as long as you pass it without parentheses.
function shout(text) {
return text.toUpperCase() + "!";
}
console.log(["hi", "hey"].map(shout)); // → ["HI!", "HEY!"]
Writing a function that takes a callback
function repeat(times, action) {
for (let i = 0; i < times; i++) {
action(i);
}
}
repeat(3, i => console.log("Step", i));
Callbacks and waiting
Callbacks were the original way to handle code that finishes later, such as loading a file or waiting for a server. That works, but long chains get hard to read, which led to promises and async/await. See Callbacks and Their Problems later.
Name the callback parameter
callback, onSuccess or handler make the purpose obvious to anyone reading your function.