Sub topic 2
What a Callback Is and How to Write One
This chapter assumes you can write functions and arrow functions in JavaScript and run a script in Node.js or the browser console. It also builds on the previous chapter: functions are values, so you can store them in variables and pass them around.
The definition
A callback is a function you pass as an argument to another function, so that the other function can call it later. The function that receives the callback decides when to call it, how many times, and with which arguments.
The word "later" can mean "a moment from now, before the outer function returns" or "after some event happens." This chapter covers the mechanics that both cases share. The next two chapters cover the synchronous case and the asynchronous case separately.
function greet(name) {
console.log('Hello, ' + name);
}
function processUser(name, callback) {
const trimmed = name.trim();
callback(trimmed);
}
processUser(' Ada ', greet); // Hello, AdaHere greet is the callback. processUser receives it under the parameter name callback and calls it once with the cleaned-up name.
Writing a function that accepts a callback
When you write a function that takes a callback, you have three decisions to make:
- Which arguments the callback receives. Document them, because the caller writes the callback to match.
- When it is called. It can be called once at the end, once per item, or only on some condition.
- What happens to its return value. You can ignore it, as
forEachdoes, or use it, asmapdoes.
This example uses the callback's return value to decide which items to keep:
function keepIf(items, test) {
const result = [];
for (const item of items) {
if (test(item)) {
result.push(item);
}
}
return result;
}
const evens = keepIf([1, 2, 3, 4], (n) => n % 2 === 0);
console.log(evens); // [ 2, 4 ]The caller passed an inline arrow function. A named function works the same way. Pick whichever reads more clearly at the call site.
Common errors
Calling the function instead of passing it
This is the most frequent mistake:
function greet(name) {
console.log('Hello, ' + name);
}
function processUser(name, callback) {
callback(name.trim());
}
try {
processUser('Ada', greet()); // greet runs now and returns undefined
} catch (err) {
console.log(err.message); // callback is not a function
}greet() runs greet immediately and passes its return value, undefined, as the argument. Pass greet without parentheses. If you need to supply extra arguments, wrap the call in an arrow function: () => greet('Ada').
Mismatched arguments
JavaScript does not check how many arguments a function receives. If your function calls callback(value, index) and the caller's callback expects (index, value), nothing fails at the call. The values are just wrong. Keep the argument order consistent and document it.
Not validating optional callbacks
If a callback is optional, check it before you call it:
function save(data, onDone) {
console.log('Saving', data);
if (typeof onDone === 'function') {
onDone(data);
}
}
save({ id: 1 }); // no callback, no error
save({ id: 2 }, (d) => console.log('Saved', d.id));For a required callback, throw early with a clear message so the mistake surfaces at the call site:
function each(items, callback) {
if (typeof callback !== 'function') {
throw new TypeError('each: callback must be a function');
}
items.forEach((item) => callback(item));
}
each(['a', 'b'], (x) => console.log(x)); // a, bSummary
| Concept | Meaning |
|---|---|
| Callback | A function passed as an argument to be called by the receiver |
| Higher-order function | A function that takes or returns another function |
| `fn` vs `fn()` | Passing the function vs passing its return value |
| Contract | The arguments, timing, and use of the return value that the receiver promises |
Exercise
Write a function times(n, callback) that calls callback n times, passing the zero-based iteration number, and returns an array of the callback's return values. What does times(3, (i) => i * 10) return, and what goes wrong with times(3, console.log())?
Show answer
One implementation: function times(n, callback) { const out = []; for (let i = 0; i < n; i++) { out.push(callback(i)); } return out; }. times(3, (i) => i * 10) returns [0, 10, 20]. times(3, console.log()) calls console.log right away, which prints an empty line and returns undefined. Then times tries to call undefined and throws TypeError: callback is not a function. The fix is to pass console.log without parentheses.
Exercise
A function calls onResult(error, value), but a caller writes onResult = (value) => console.log(value). What gets logged on success, and why is no error raised?
Show answer
The caller's single parameter value receives the first argument, which is error (for example null on success), so it logs null. JavaScript does not enforce how many arguments a function takes or in what order, so the mismatch fails silently. The callback must declare its parameters in the documented order: (error, value) => ....