How do callbacks work in JavaScript, and why are they so useful?
A callback is a function that you hand to another function so that it can call it later. It is how JavaScript passes behaviour into code that only knows how to do one thing. The receiving function decides when to call the callback and with what, and the caller decides what the behaviour should be.
function run(task) {
console.log('before');
task();
console.log('after');
}
run(function () {
console.log('work');
});
// The same function reused with different behaviour.
function applyToAll(items, fn) {
const results = [];
for (const item of items) {
results.push(fn(item));
}
return results;
}
console.log(applyToAll([1, 2, 3], function (n) { return n * 10; }));
console.log(applyToAll([1, 2, 3], function (n) { return '#' + n; }));Because the behaviour arrives as an argument, the receiving function stays general. The array method called map knows nothing about multiplying numbers or formatting labels. It only knows that it should call your function once for each element and collect the answers, and the caller decides what that function does. That separation is the reason higher-order functions became the backbone of functional style in the language.
Callbacks also carry the idea of timing. A callback is not necessarily called straight away. It might be called later, after a timer finishes, after a network response arrives, or after the user clicks something. The receiving function owns the schedule, and the callback simply reacts when it is finally invoked. That is exactly how the built-in array methods work, because they call your function immediately while they walk the array, and how setTimeout works, because it calls yours later.
Two practical points are worth remembering. A callback that is expected to be called more than once, or not at all, needs a clear agreement about that, and the error-first convention is the traditional way of reporting failure. A callback that is passed straight through to another API should be wrapped in a new function when you need to add behaviour, so that the extra arguments do not leak through.
The next questions in this topic look at what callbacks cost in a large codebase and how promises solved those problems, so it helps to keep this idea of a callback as behaviour-in-a-box in mind.