Sub topic 2
What a Callback Is and How to Write One
This chapter assumes you can write functions and arrow functions, work with arrays and objects, and run a script in Node.js or the browser console. It also builds on the previous chapter: functions are values, so they can be stored in variables, put in objects, and passed to other functions.
Here you will learn what a callback is, how to write functions that accept one, and the mistakes people make most often when passing them around. Later chapters cover when callbacks run (synchronously or asynchronously) and how the event loop schedules them.
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 is called a higher-order function: a function that takes a function as an argument, returns one, or both.
The name comes from the relationship between the two functions. You hand over a function, and the receiver "calls you back" by invoking it at the moment it chooses.
function greet(name, format) {
const message = format(name);
console.log(message);
}
function shout(text) {
return text.toUpperCase() + '!';
}
greet('ada', shout); // ADA!
greet('ada', (text) => `Hello, ${text}.`); // Hello, ada.greet does not know how the greeting should look. It knows when to format (after receiving a name) and what to do with the result (log it). The caller supplies the formatting logic as a callback. Every callback API divides the work this way: the higher-order function owns the control flow, and the callback supplies one piece of behavior.
Passing a Function vs. Calling It
The most common beginner bug with callbacks is adding parentheses. shout is a reference to the function. shout() calls the function immediately and evaluates to whatever it returns.
function greet(name, format) {
console.log(format(name));
}
function shout(text) {
return String(text).toUpperCase() + '!';
}
greet('ada', shout); // Correct: passes the function. Logs "ADA!"
try {
greet('ada', shout()); // Wrong: calls shout(undefined) first
} catch (err) {
console.log(err.message); // format is not a function
}In the wrong version, shout() runs right away with no argument and returns the string 'UNDEFINED!'. That string is what greet receives as format, and calling a string throws TypeError: format is not a function.
If you need to pass arguments that the higher-order function will not supply, wrap the call in an arrow function. The wrapper is a new function, so nothing runs until the higher-order function calls it:
function runLater(callback) {
console.log('about to run callback');
callback();
}
function logWithPrefix(prefix, text) {
console.log(`${prefix}: ${text}`);
}
runLater(() => logWithPrefix('INFO', 'started'));
// about to run callback
// INFO: startedWays to Write the Callback
Any function value can be a callback. The forms differ in readability and in how they treat this. The this differences get their own chapter later.
| Form | Example | When it fits |
|---|---|---|
| Named function declaration | `greet('ada', shout)` | Reused logic, or code where a name explains intent and shows up in stack traces |
| Anonymous function expression | `greet('ada', function (t) { return t; })` | Older code, or when you need a dynamic `this` |
| Arrow function | `greet('ada', (t) => t.trim())` | Short, one-off logic; inherits `this` from the surrounding scope |
| Bound method | `greet('ada', formatter.format.bind(formatter))` | Passing an object's method while keeping its `this` |
Named functions are easy to overlook. An inline arrow is convenient, but once a callback grows past a few lines, giving it a name usually makes the calling code easier to read. Chapter 10 builds on this when flattening nested callbacks.
Writing Functions That Accept Callbacks
Writing a higher-order function means making three decisions:
- When the callback is invoked, and how many times.
- What arguments it receives.
- What happens to its return value, if anything.
Together, these three answers form the function's contract. Callers rely on it, so document it and keep it stable.
Passing arguments to the callback
The higher-order function decides what the callback receives. Here forEachEntry iterates over an object and passes the value, key, and the object itself, in the same order that array methods use:
function forEachEntry(obj, callback) {
for (const key of Object.keys(obj)) {
callback(obj[key], key, obj);
}
}
const stock = { apples: 4, pears: 0, plums: 7 };
forEachEntry(stock, (count, fruit) => {
console.log(`${fruit}: ${count}`);
});
// apples: 4
// pears: 0
// plums: 7The callback declares only the two parameters it uses. JavaScript does not enforce arity, so extra arguments are silently ignored, and missing arguments arrive as undefined.
Using the callback's return value
Some callbacks are called only for their side effects. Others return a value that the higher-order function uses. A predicate is a callback that returns true or false to answer a question:
function countWhere(items, predicate) {
let count = 0;
for (const item of items) {
if (predicate(item)) count++;
}
return count;
}
const temps = [12, 25, 31, 18, 29];
console.log(countWhere(temps, (t) => t > 24)); // 3If the callback forgets to return, the higher-order function receives undefined. That is falsy, so countWhere would quietly return 0. Arrow functions with a block body need an explicit return:
function countWhere(items, predicate) {
let count = 0;
for (const item of items) {
if (predicate(item)) count++;
}
return count;
}
const temps = [12, 25, 31, 18, 29];
console.log(countWhere(temps, (t) => { t > 24; })); // 0 (bug: no return)
console.log(countWhere(temps, (t) => { return t > 24; })); // 3
console.log(countWhere(temps, (t) => t > 24)); // 3 (concise body)Accepting more than one callback
A function can accept several callbacks, one for each outcome. This pattern appears in older browser APIs such as navigator.geolocation.getCurrentPosition(success, error):
function parseAge(input, onSuccess, onFailure) {
const age = Number(input);
if (Number.isInteger(age) && age >= 0) {
onSuccess(age);
} else {
onFailure(new Error(`Invalid age: ${input}`));
}
}
parseAge('42', (age) => console.log('Age is', age), (err) => console.log(err.message));
// Age is 42
parseAge('-3', (age) => console.log('Age is', age), (err) => console.log(err.message));
// Invalid age: -3The contract here says that exactly one of the two callbacks runs, exactly once. Node.js chose a different shape, a single callback with the error as its first argument. Chapter 8 covers that convention.
Validating and defaulting callbacks
If a caller passes something that is not a function, the failure shows up wherever the callback is eventually invoked, which may be far from the real mistake. Checking at the boundary gives a clearer error:
function retry(times, task) {
if (typeof task !== 'function') {
throw new TypeError(`task must be a function, got ${typeof task}`);
}
for (let attempt = 1; attempt <= times; attempt++) {
if (task(attempt)) return attempt;
}
return -1;
}
console.log(retry(5, (n) => n === 3)); // 3
try {
retry(5, 'not a function');
} catch (err) {
console.log(err.message); // task must be a function, got string
}When a callback is optional, give it a default no-op function so the body can call it without checking each time:
function saveSetting(store, key, value, onSaved = () => {}) {
store[key] = value;
onSaved(key, value);
}
const settings = {};
saveSetting(settings, 'theme', 'dark');
saveSetting(settings, 'lang', 'en', (k, v) => console.log(`saved ${k}=${v}`));
// saved lang=en
console.log(settings); // { theme: 'dark', lang: 'en' }Default parameters apply only when the argument is undefined. If someone passes null, the default is skipped and the call throws. Combine the default with a typeof check if callers might pass null.
Common Errors
Passing a function whose parameters don't match
Because JavaScript ignores arity, it is easy to pass an existing function that interprets the extra arguments in an unexpected way. The classic example:
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
console.log(['1', '2', '3'].map((s) => parseInt(s, 10))); // [1, 2, 3]map calls its callback with (element, index, array). parseInt takes (string, radix), so it receives the index as the radix: parseInt('2', 1) is NaN. The wrapper arrow passes only what you intend.
Losing context when passing a method
greet('ada', formatter.format) passes the function without its object, so this inside format will not be formatter. Fix it with .bind(formatter) or (t) => formatter.format(t). Chapter 7 explains why.
Assuming when the callback runs
Taking a callback says nothing about timing. countWhere calls its predicate before it returns. setTimeout calls its callback later, after the current code has finished. Code that reads a value the callback sets must know which kind it is dealing with. Chapters 3 and 4 cover each kind.
Quick Reference
| Question | Answer |
|---|---|
| What is a callback? | A function passed as an argument so another function can invoke it |
| What receives it? | A higher-order function |
| Who decides when it runs? | The higher-order function, not the caller |
| How do I pass extra arguments? | Wrap it: `() => fn(a, b)` |
| What if the callback returns nothing? | The receiver gets `undefined` |
| How do I make it optional? | Default parameter: `callback = () => {}` |
Exercise
This code logs "Done!" immediately and then throws a TypeError. Explain why, and fix it so "Done!" is logged by runTask after "working".
function runTask(onDone) {
console.log('working');
onDone();
}
function report(msg) {
console.log(msg);
}
runTask(report('Done!'));
Show answer
report('Done!') runs before runTask is called, so "Done!" is logged first. report returns undefined, so onDone is undefined, and onDone() throws "onDone is not a function". Pass a function that calls report later: runTask(() => report('Done!'));. This logs "working" and then "Done!".
Exercise
Write a function times(n, callback) that calls callback n times, passing the zero-based iteration index, and returns an array of the callback's return values. It should throw a TypeError if callback is not a function. What does times(3, (i) => i * i) return?
Show answer
function times(n, callback) {
if (typeof callback !== 'function') {
throw new TypeError('callback must be a function');
}
const results = [];
for (let i = 0; i < n; i++) {
results.push(callback(i));
}
return results;
}
times(3, (i) => i * i) returns [0, 1, 4].
Exercise
Why does ['10', '10', '10'].map(parseInt) return [10, NaN, 2]?
Show answer
map passes (element, index, array), so the calls are parseInt('10', 0), parseInt('10', 1), and parseInt('10', 2). A radix of 0 is treated as the default base 10, which gives 10. Radix 1 is invalid, which gives NaN. In base 2, '10' is 2. Use map((s) => parseInt(s, 10)) instead.