Callbacks
A callback is a function you hand to another function so that it can be called later. It is the oldest way JavaScript expresses "do this when that finishes".
Detailed Explanation
In JavaScript, functions are values. You can store one in a variable, put one in an array, and pass one as an argument. A callback is nothing more than that last case: a function passed as an argument, to be invoked by the receiving code at a time of its choosing.
There are two flavours, and confusing them causes most callback bugs.
A synchronous callback runs before the outer function returns. array.map(fn) calls fn once per element, immediately, and hands you the finished array. Nothing is deferred.
An asynchronous callback is stored somewhere and invoked later, after the current call stack empties. setTimeout(fn, 1000) returns instantly; fn runs about a second later. Reading a file in Node works the same way. The function that accepted the callback has long since returned by the time the callback fires.
Callbacks exist because JavaScript has one thread. If reading a file blocked that thread, the browser would freeze. So the runtime takes your callback, starts the slow work elsewhere, and puts your function on a queue when the work finishes. The event loop picks it up. Before promises landed in ES6, this was the only way to write non-blocking code.
Node.js standardised a convention called error-first callbacks: the callback's first parameter is an error (or null), and results come after. This matters because you cannot try/catch around an asynchronous callback. The try block finishes long before the callback throws, so the error escapes to the top level.
The cost of callbacks is structural. Each dependent step nests inside the previous one, and the code drifts rightward into what people call callback hell. Error handling gets duplicated at every level, because there is no shared failure path. Control flow that would be four flat lines with await becomes a pyramid.
A subtler cost: a callback closes over the variables in scope where it was written. That closure keeps those variables alive in memory until the callback is released. A forgotten event listener holding a large object is a common leak.
Reach for callbacks today when the API gives you no choice, when the callback is synchronous (sort, filter, reduce), or when the thing can fire many times. Promises resolve exactly once, so an event listener or a stream handler is still callback-shaped. For a one-shot asynchronous result, use a promise and async/await instead. Node offers util.promisify to convert an error-first function into a promise-returning one.
Code Examples
Synchronous callback: runs immediately, once per element.
// Synchronous callback: runs immediately, once per element.
const prices = [10, 20, 30];
const withTax = prices.map((p) => p * 1.2);
console.log(withTax); // => [12, 24, 36]
// Asynchronous callback: the log order shows the deferral.
console.log("first");
setTimeout(() => console.log("third"), 0); // queued, not immediate
console.log("second");
// => first
// => second
// => thirdNode's error-first convention, and why try/catch does not help.
// Node's error-first convention, and why try/catch does not help.
function loadUser(id, callback) {
setTimeout(() => {
if (!id) return callback(new Error("id required")); // error goes to arg 1
callback(null, { id, name: "Ada" }); // null error, then the value
}, 10);
}
try {
loadUser(null, (err, user) => {
if (err) console.log("handled:", err.message); // => handled: id required
else console.log(user);
});
} catch (e) {
// Never reached. The try block exits before the callback runs.
console.log("this never prints");
}Common Gotchas
try/catch does not wrap async callbacks
the `try` block completes before the callback is invoked, so a throw inside the callback becomes an uncaught exception. Handle errors inside the callback itself.
A detached method loses `this`
passing `obj.handler` as a callback passes the function only, not the object. Use `obj.handler.bind(obj)` or an arrow function wrapper.
Calling the callback twice
a callback invoked on both the success and error path runs your continuation twice. Always `return callback(...)` when you branch.
Callbacks can fire many times
promises settle once, so events and streams remain callback-based by design, not by legacy.