What is a callback function?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
A callback is a function you hand to another function so it can be called later. In asynchronous code it answers the question "what should happen once this finishes?" without blocking everything in the meantime.
function loadUser(id, callback) {
setTimeout(() => {
callback({ id, name: "Mai" });
}, 500);
}
loadUser(1, (user) => console.log(user.name));
console.log("this line runs first");
Because JavaScript runs on a single thread, blocking while waiting for a network request would freeze the whole page. Instead the runtime keeps going and invokes your callback when the result arrives.
The error-first convention
Node-style APIs pass an error as the first argument, so you always check it before touching the data:
fs.readFile("data.json", (err, data) => {
if (err) return console.error(err);
console.log(data);
});
Why promises replaced them
Chaining dependent async steps with callbacks nests deeper at every level — the shape people call callback hell:
loadUser(1, (user) => {
loadPosts(user.id, (posts) => {
loadComments(posts[0].id, (comments) => {
// three levels deep, and error handling is duplicated at each one
});
});
});
Promises and async/await flatten this and give one place to catch errors. Callbacks have not disappeared though: map, filter, addEventListener and setTimeout all still take one. The pattern is fine — it is specifically chaining asynchronous callbacks that ages badly.
