What is a callback function?
A callback is a function you pass to another function so it can be called later, either right away (synchronous callbacks like map) or when something finishes (asynchronous callbacks like timers and event handlers).
Synchronous callbacks
Array methods (map, filter, sort), forEach, and custom higher-order functions call your function immediately, as part of their own work.
Asynchronous callbacks
setTimeout, addEventListener, and older Node APIs (fs.readFile(path, cb)) store your function and call it later from the event loop. Node's convention is the error-first callback: (err, result) => {}.
Problems with async callbacks
- Callback hell: nested callbacks that are hard to read and harder to handle errors in.
- Inversion of control: you trust the other code to call your callback exactly once, with the right arguments.
- Error handling:
try/catcharound the outer call cannot catch errors thrown later inside the callback.
Promises and async/await were created to fix these problems. Today callbacks are still everywhere for events and array methods, while one-off async results usually use promises.
Tip
You can turn a callback API into a promise with new Promise(...), or in Node with util.promisify.
Code example
1// Synchronous callback: called immediately by map2const prices = [10, 20, 30];3const withTax = prices.map((p) => p * 1.2);4console.log(withTax); // [12, 24, 36]56// Asynchronous, error-first callback (Node style)7function loadUser(id, callback) {8 setTimeout(() => {9 if (id <= 0) callback(new Error("Invalid id"));10 else callback(null, { id, name: "Ada" });11 }, 50);12}1314loadUser(1, (err, user) => {15 if (err) return console.log("Failed:", err.message);16 console.log("Loaded:", user.name); // Loaded: Ada17});1819// Wrapping a callback API in a promise20const loadUserAsync = (id) =>21 new Promise((resolve, reject) => loadUser(id, (err, user) => (err ? reject(err) : resolve(user))));2223const user = await loadUserAsync(2);24console.log("Awaited:", user.id); // Awaited: 2
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.