Callbacks
A function you pass into another function, to be called later — often once some work finishes.
What is it?
Functions are values, so you can pass one function to another as an argument. A callback is a function you pass in to be called at the right moment: after a click, after a timer, or for every item in an array.
You've already used callbacks: the function you pass to .map(), addEventListener() or setTimeout() is one.
Explain like I'm 10
It's like telling a restaurant host: 'Call this number when our table is ready.' You don't wait at the counter. You hand over instructions (the callback) and get on with your day.
Examples
A function that accepts a callback
function greetUser(name, onDone) {
const message = "Hi, " + name + "!";
onDone(message); // calling the callback with the result
}
greetUser("Amara", (message) => {
console.log(message); // "Hi, Amara!"
});Two different callbacks for success and failure
function checkAge(age, onAllowed, onDenied) {
if (age >= 18) {
onAllowed();
} else {
onDenied();
}
}
checkAge(
20,
() => console.log("Access granted"),
() => console.log("Access denied")
);
// logs "Access granted"A function can take more than one callback. Here exactly one of the two runs, depending on the outcome.
How it works
Nothing special happens underneath. A callback is a regular function value, stored in a parameter and called whenever the receiving code decides. What makes it a "callback" is its role: someone else's code calls it back later, instead of your code calling it directly.
Why does it exist?
Callbacks keep a function flexible without it knowing the details in advance. .map() doesn't know what transformation you want; addEventListener doesn't know what should happen on click. The callback supplies that missing piece.
When to use it
Use a callback to customize what happens at a point inside another function: reacting to an event, running code for each array item, or deciding what happens when an async task finishes.
When not to use it
If you're nesting many callbacks for a sequence of async steps, use promises and async/await instead. They were built to replace exactly that pattern.
Common mistakes
Confusing
callbackwithcallback()— passing the function itself, not the result of calling it.Forgetting that a callback might run asynchronously, and expecting code after it to have access to its result immediately.
Nesting many callbacks inside each other, producing hard-to-read 'callback hell'.
Practice exercises
- Easy:
Write a function
runTwice(fn)that calls the given function twice in a row. - Medium:
Write a function
processArray(arr, callback)that calls callback once for every item (essentially rebuilding forEach). - Hard:
Write a function that takes a callback and calls it after a 1-second delay, using
setTimeout.
Interview questions
What is a callback function?
A function passed into another function, which calls it at the right moment: after an event, after a delay, or once per item in a collection.
Are all callbacks asynchronous?
No. "Callback" describes a role (being called by other code), not timing. Callbacks for array methods like map/forEach run synchronously during the call; callbacks for setTimeout or event listeners run later, asynchronously.
What does this log, in order? `console.log("start"); [1, 2, 3].forEach((n) => console.log(n)); console.log("end");`
start, 1, 2, 3, end. forEach's callback runs synchronously and finishes before the next line runs.
What does this log, in order? `console.log("start"); setTimeout(() => console.log("timeout"), 0); console.log("end");`
start, end, timeout. Even a 0ms delay doesn't run immediately: the callback goes to the event loop's task queue and runs only after the current synchronous code (including console.log("end")) finishes.
What is the 'error-first callback' convention?
A pattern (common in Node.js-style APIs) where the callback's first parameter is an error (null if none) and the result comes second: (err, data) => {}. Callers check err before trusting data, so every callback handles errors the same way.
What is 'callback hell', and what causes it?
A pyramid of deeply nested callbacks, one per step of an async sequence. Each step can only run inside the previous step's callback, and error handling is repeated at every level. Promises and async/await exist largely to flatten this.
What's the difference between passing `fn` and `fn()` as a callback?
fn passes the function itself, to be called later. fn() calls it now and passes its return value instead, a very common bug when you meant to defer the call.
What does this log? `function greet() { console.log("hi"); } setTimeout(greet(), 1000);`
"hi" logs immediately. greet() runs while building setTimeout's arguments, and its return value (undefined) is what gets scheduled, which does nothing a second later.
What's the bug here? `const counter = { count: 0, increment() { this.count++; } }; setTimeout(counter.increment, 0);`
counter.increment passes the bare function, detached from counter. setTimeout calls it with no receiver, so this isn't counter and this.count++ doesn't update it. Fix with .bind(counter) or an arrow function: () => counter.increment().
How do promises address the problems that deeply nested callbacks create?
A promise represents one eventual result. You chain .then() calls at the same level instead of nesting them, and errors flow to a single .catch() instead of being checked at every level.
How would you write a function that accepts an optional callback safely?
Check it's a function before calling it (if (typeof callback === "function") callback(result);), or give the parameter a no-op default, so calling without a callback doesn't throw.
What happens here? `function fetchData(callback) { const data = { id: 1 }; callback(data); } fetchData();`
It throws TypeError: callback is not a function. No callback was passed, so it's undefined, which can't be called. The function should guard against a missing callback.
Does a callback's return value always matter to the code that calls it?
It depends on the caller. map's callback return values build the new array, and reduce's becomes the next accumulator. Callbacks passed to forEach, addEventListener or setTimeout have their return values ignored.
What's the difference between a 'callback' and an 'event handler'?
An event handler is a callback in a specific role: registered to run when an event (a click, a message, a timer) occurs. "Callback" is the general term for any function handed to other code to call later.
Why does naming a callback function instead of passing it as an inline anonymous function sometimes help debugging?
A named function appears by name in stack traces and profiler output, and can be reused or tested on its own. An anonymous inline callback shows as <anonymous>, making it harder to find which one threw among many similar callbacks.
If a function accepts multiple callbacks, like `onSuccess` and `onError`, what determines which one runs?
The function's own logic. The callbacks are ordinary parameters, and the function's code decides, based on a condition it checks, which one (if any) to call.