Introduction & Syntax
Callbacks · Study material
A callback is a function passed to another function, to be called by it – now (like the function you give to map) or later (when a timer fires, a file is read or a button is clicked). Callbacks were JavaScript's first tool for asynchronous code, and they still power array methods, event listeners, timers and many Node.js APIs. Interviews ask about the order in which callbacks run, the error-first convention, callback hell, inversion of control and how promises improve on callbacks. This topic covers all of that. Then test yourself with 60 practice questions – 15 MCQs, 20 predict-the-output puzzles, 15 debugging questions and 10 coding problems – every one run on Node.js.
Synchronous callbacks
Many callbacks run immediately, while the function that received them is still running: the callbacks of forEach, map, filter, sort and of your own helpers. Code after the call runs only when all of them have finished.
// A callback is a function passed to another function, which decides when to call it
function repeat(times, callback) {
for (let i = 1; i <= times; i++) callback(i); // called right now, during repeat()
}
repeat(3, (n) => console.log(`step ${n}`));
// Array methods take synchronous callbacks too
const prices = [499, 99, 1499];
console.log(prices.filter((p) => p < 1000), [..."cba"].sort((a, b) => a.localeCompare(b)));
step 1 step 2 step 3 [ 499, 99 ] [ 'a', 'b', 'c' ]
Asynchronous callbacks
Callbacks given to timers, network requests, file reads and event listeners run later, after the current code has finished and the engine is free – even setTimeout(fn, 0) waits. The Event Loop topic explains the exact order; here, remember: synchronous code first, then callbacks, timers in order of their delay.
console.log("1. order placed");
// An asynchronous callback runs LATER – after the current code has finished – even with a 0 ms delay
setTimeout(() => console.log("3. order confirmed (callback)"), 0);
console.log("2. showing receipt");
1. order placed 2. showing receipt 3. order confirmed (callback)
Passing callbacks and their arguments
Pass the function itself (notify), not the result of calling it (notify()). To supply arguments, wrap the call in an arrow function, or use the extra parameters that setTimeout forwards to the callback.
function notify(user, channel) {
console.log(`Notify ${user} via ${channel}`);
}
setTimeout(notify, 10, "Asha", "email"); // extra setTimeout arguments are passed to the callback
setTimeout(() => notify("Ravi", "sms"), 0); // or wrap the call in an arrow function
Notify Ravi via sms Notify Asha via email
Error-first callbacks
Node.js APIs follow a convention: the callback's first parameter is an error (null on success) and the result comes after it. Always check the error first and return after handling it, so the success code does not run too.
// Node.js convention: callback(error, result) – error is null on success
function fetchUser(id, callback) {
setTimeout(() => {
if (id <= 0) callback(new Error("Invalid id"));
else callback(null, { id, name: id === 1 ? "Asha" : "Ravi" });
}, 0);
}
const handle = (err, user) => {
if (err) return console.log("Error:", err.message); // return: stop here on error
console.log("User:", user.name);
};
fetchUser(1, handle);
fetchUser(-5, handle);
User: Asha Error: Invalid id
Callback hell
When each asynchronous step needs the previous step's result, callbacks nest inside callbacks, and the code becomes a rightward "pyramid of doom" that is hard to read, handle errors in and change. Named functions flatten it (see Coding Techniques); promises and async/await solve it properly.
function step(name, value, cb) {
setTimeout(() => cb(null, `${value} → ${name}`), 0);
}
// Each step depends on the previous one, so the code drifts to the right: the "pyramid of doom"
step("validate", "order", (e1, a) => {
step("charge", a, (e2, b) => {
step("ship", b, (e3, c) => {
console.log(c);
});
});
});
order → validate → charge → ship
Inversion of control
Passing a callback means trusting the other code to call it correctly – exactly once, with the right arguments, at the right time. Buggy or malicious code may call it twice, never, too early or synchronously when you expected async. You can guard against some of this (e.g. with a once wrapper); promises solve it by design, because a promise settles only once.
// Passing a callback hands control to someone else's code. Protect yourself against misuse.
function onceOnly(cb) {
let called = false;
return (...args) => {
if (called) return console.log("ignored extra call");
called = true;
cb(...args);
};
}
function buggyPaymentLibrary(cb) { // third-party code that calls back twice
cb("paid");
cb("paid");
}
buggyPaymentLibrary(onceOnly((status) => console.log("charge customer:", status)));
charge customer: paid ignored extra call
From callbacks to promises
A small adapter turns any error-first callback API into a function that returns a promise – Node.js ships one as util.promisify. Promises (next topic) and async/await (the topic after) are built on this idea.
function readConfig(name, cb) {
setTimeout(() => (name ? cb(null, { name, debug: false }) : cb(new Error("No name given"))), 0);
}
// Wrap an error-first callback API in a Promise: the bridge to promises and async/await
const promisify = (fn) => (...args) =>
new Promise((resolve, reject) => fn(...args, (err, data) => (err ? reject(err) : resolve(data))));
const readConfigAsync = promisify(readConfig);
readConfigAsync("app").then((c) => console.log("loaded", c.name));
readConfigAsync("").catch((e) => console.log("failed:", e.message));
loaded app failed: No name given
Common mistakes
- Passing fn() instead of fn – you pass its return value, not the function.
- Using an async result immediately – the callback has not run yet.
- Forgetting return after the error branch – the callback runs twice.
- Swapping the parameters – (data, err) instead of (err, data).
- Wrapping async code in try/catch – errors thrown later in callbacks are not caught.
- Calling the callback sometimes synchronously, sometimes asynchronously – unpredictable order.
- Collecting parallel results with push – they arrive in finish order, not request order.
Key points to remember
- A callback is a function passed to another function to be called by it.
- Array-method callbacks are synchronous; timer and I/O callbacks are asynchronous.
- Async callbacks run after the current code, even with a 0 ms delay.
- Error-first: callback(err, result); check err and return.
- Deep nesting = callback hell; flatten with named functions or use promises.
- Callbacks give control to other code (inversion of control).
- promisify turns callback APIs into promise APIs.
Frequently asked questions
Are callbacks outdated?
No. Synchronous callbacks (map, filter, sort) and event listeners are everywhere. For sequences of asynchronous steps, though, promises and async/await are clearer than nested callbacks.
Is every callback asynchronous?
No – being a callback says nothing about timing. forEach calls its callback immediately; setTimeout calls it later. Good APIs are consistent: always sync or always async.
Why does Node.js put the error first?
It makes error handling impossible to overlook: every callback must deal with the first argument before using the result.
Where can I learn more?
Read Higher-Order Functions, The Event Loop and Promises in the JavaScript tutorial, then practise with the exercises below.