Skip to content

Callback Functions

A callback is a function passed to another function as an argument, so that the receiving function can call it at the right moment. JavaScript treats functions as values, so a function can be handed around like a number or a string.

Many built-in methods take a callback. forEach() calls its callback once for each element of an array, and passes it the element and its index:

const tasks = ['Water plants', 'Pay gas bill', 'Book dentist'];
function announce(task, index) {
console.log(`${index + 1}. ${task}`);
}
tasks.forEach(announce);

This prints:

1. Water plants
2. Pay gas bill
3. Book dentist

setTimeout() takes a callback and a delay in milliseconds, and any further arguments are passed on to the callback when it runs:

function remind(task) {
console.log(`Reminder: ${task}`);
}
setTimeout(remind, 50, 'Pay gas bill');
console.log('Reminder set');

This prints:

Reminder set
Reminder: Pay gas bill

The callback to forEach() runs straight away, before forEach() returns, which makes it a synchronous callback. The callback to setTimeout() runs later, after the rest of the script has finished, which makes it an asynchronous one. Synchronous vs Asynchronous explains the difference.

Some browser APIs take two callbacks, one for success and one for failure. getCurrentPosition() asks for the user’s location and calls whichever callback fits the outcome:

navigator.geolocation.getCurrentPosition(
(position) => console.log(position.coords.latitude, position.coords.longitude),
(error) => console.log(`No location: ${error.message}`),
);

In a browser, this asks the user for permission to share their location. If they allow it, the first callback logs their latitude and longitude, and if they refuse, the second logs the reason.

A function that accepts a callback can leave part of its job to the caller. convertAll() loops over the readings, while the callback decides what each conversion does:

function convertAll(readings, convert) {
const results = [];
for (const reading of readings) {
results.push(convert(reading));
}
return results;
}
const toFahrenheit = (c) => c * 9 / 5 + 32;
const toKelvin = (c) => c + 273.15;
console.log(convertAll([0, 20, 37], toFahrenheit));
console.log(convertAll([0, 20, 37], toKelvin));
console.log(convertAll([0, 20, 37], (c) => `${c}°C`));

This prints:

[ 32, 68, 98.6 ]
[ 273.15, 293.15, 310.15 ]
[ '0°C', '20°C', '37°C' ]

The last call passes an arrow function written in place, which is the usual style for a callback that is needed only once.

A callback is passed by name, without parentheses. Adding parentheses calls the function at once and passes its return value instead:

function remind(task) {
console.log(`Reminder: ${task}`);
}
try {
setTimeout(remind('Pay gas bill'), 50);
} catch (err) {
console.log(err.name);
}

This prints:

Reminder: Pay gas bill
TypeError

The reminder appears immediately, and setTimeout() receives undefined, which Node rejects with a TypeError. A browser does not throw, so the mistake goes unnoticed there. To pass arguments, either list them after the delay as shown earlier, or wrap the call in an arrow function: setTimeout(() => remind('Pay gas bill'), 50).

Steve Griffith covers this topic in his video JavaScript Callback Functions.