Callbacks
Callbacks are JavaScript's oldest async pattern — functions passed as arguments and called later when an operation completes. Understanding callbacks is essential because Promises and async/await are built on the same concept.
What is a callback in JavaScript?
A callback is a function you pass to another function so it can be called later: when an event happens, when a timer fires, or for each item in an array. button.addEventListener("click", handleClick) and [1, 2].map(n => n * 2) both use callbacks. Deeply nested asynchronous callbacks ("callback hell") are why promises and async/await were introduced.
setTimeout(() => console.log("1 second later"), 1000);
[3, 1, 2].sort((a, b) => a - b);
// Node-style error-first callback
fs.readFile("a.txt", "utf8", (err, data) => {
if (err) return console.error(err);
console.log(data);
});Callback Types
Called immediately within the current execution. Examples: Array.map, Array.filter, Array.sort.
Called later, after the current call stack is empty. Examples: setTimeout, fetch, fs.readFile.
Called when a specific event fires. Examples: addEventListener, on('data'), on('error').
First argument is always an error (or null). Second is the result. Standardises error handling.
Callback vs Promises vs async/await
Useful Callback Utilities
once(fn)function once(fn) {
let called = false;
return (...args) => {
if (called) return;
called = true;
return fn(...args);
};
}promisify(fn)function promisify(fn) {
return (...args) => new Promise((res, rej) => {
fn(...args, (err, result) =>
err ? rej(err) : res(result)
);
});
}debounce(fn, ms)function debounce(fn, ms) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}after(n, fn)function after(n, fn) {
let count = 0;
return (...args) => {
if (++count === n) fn(...args);
};
}
// Run fn only after 3 callbacks completeCommon Pitfalls
Interactive Callback Demo
Code Editor
<button id="go">Run</button>
<ol id="out"></ol>Preview
Callbacks — step by step
What is a callback function
A callback is a function passed as an argument to another function, to be invoked at a later time — after an asynchronous operation completes or when a specific event occurs. Callbacks are the foundation of JavaScript's async model: setTimeout, addEventListener, array methods like map/filter all use them.
🎯 Quick Check
What is the main problem with deeply nested callbacks?
JavaScript Callbacks: summary
Key points
- Synchronous callbacks run immediately (
map,forEach); asynchronous ones run later (setTimeout, events). - Error-first callbacks take
(err, result), a Node.js convention. - Convert callback APIs to promises with
util.promisifyor by wrapping them innew Promise.
Frequently asked questions
›What is callback hell?
Several asynchronous steps nested inside each other's callbacks, which makes code drift right and become hard to follow. Promises and async/await flatten it.