Explain it simply
Explain it simply
At a busy restaurant, the host takes your phone number and says "we will call you when a table is free". You only hand over the number; the restaurant decides when to call. A callback is that phone number: you give a function to another function, and the receiving function calls it back when the time is right.
In JavaScript, functions are values just like numbers and strings, so you can store them in variables and pass them as arguments. An array's map() calls your callback for every item, while setTimeout() calls it once the time is up.
Problem → Why → Solution
The problem: two parentheses make the callback run too early
Say you want to send an email after an order is processed, so you pass sendEmail to processOrder as a callback. Writing sendEmail() with parentheses calls it immediately, before processOrder even starts, and it crashes because there is no order yet. In a browser, setTimeout(showBanner(), 3000) has the same flaw: the banner appears at once instead of after three seconds.
function processOrder(order, onDone) {
console.log("Processing order", order.id);
onDone(order);
}
function sendEmail(order) {
console.log("Email sent for order", order.id);
}
processOrder({ id: 7 }, sendEmail());
// TypeError: Cannot read properties of undefined (reading 'id')
// sendEmail ran first, with no argument, before processOrder startedWhy does this happen?
JavaScript evaluates every argument before calling a function. sendEmail() means "run this function now and give me its result". sendEmail returns nothing, so the result is undefined, and worse, it runs without an order and crashes. Writing sendEmail without parentheses passes the function itself, and processOrder calls it when its own work is done.
Core concept: the receiver decides when to call
A callback is a function passed as an argument. This works because functions in JavaScript are first-class values: you can store them, return them and pass them around. Passing a callback hands over control: the receiving function decides when to call it, how many times, and with which arguments.
There are two kinds. A synchronous callback is called right away, inside the receiving function, and everything finishes before that function returns; map(), filter(), forEach() and sort() work this way. An asynchronous callback is called later: when a timer fires, when the user clicks, when a file has been read. By then, the code that passed the callback has long since moved on.
| Kind | When it runs | Examples |
|---|---|---|
| Synchronous | Before the receiving function returns | map, filter, forEach, sort |
| Asynchronous | Later, after the current code finishes | setTimeout, addEventListener, fs.readFile |
Every callback carries an unwritten contract: which arguments it receives, whether its return value is used (map uses it, forEach ignores it), how many times it is called, and how errors are reported. Node.js's classic APIs use the error-first style: callback(err, result), where the first argument is an error (or null) and the second is the result. Chaining async steps means nesting callbacks inside callbacks, which pushes code to the right and makes errors hard to handle. That is exactly why Promises and async/await were introduced.
Handing over control also means handing over trust. Once a third-party library has your callback, whether it calls it exactly once, forgets to call it, or calls it twice is no longer up to you. This problem is called inversion of control, and the guarantee that a Promise settles only once is what solves it.
- Pass the function, no parentheses
- The receiver keeps the reference
- Receiver calls callback(args) when ready
- If async, your code has moved on
name is the function itself; name() is the result of calling it right now.
General pattern
function receiver(data, callback) {
// ...do some work, now or later...
callback(resultValue); // receiver decides when
}
receiver(input, handleResult); // pass a named function
receiver(input, (value) => { // or an inline arrow
// use value
});
// Node-style error-first callback
callback(error, result); // error is null on successThe receiver accepts the callback as a parameter and calls it when its work is done. The caller can pass a named function without parentheses or write an inline arrow function.
Example: an immediate callback, array callbacks and timer callbacks
This example shows three kinds of callback. greet() calls its callback straight away, and map and filter call theirs synchronously for every item. In the last part, step() calls back later through setTimeout, so notice that "Timers scheduled" is printed before any step output.
// 1. A basic callback: greet() decides when to call it
function greet(name, callback) {
console.log(`Hello, ${name}!`);
callback();
}
greet("Aung Kyaw", function () {
console.log("Callback executed!");
});
// 2. Synchronous callbacks in array methods
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function (num) {
return num * 2;
});
console.log(`Doubled: ${doubled}`);
// an arrow function works the same way
const evens = numbers.filter((num) => num % 2 === 0);
console.log(`Evens: ${evens}`);
// 3. Asynchronous callbacks: each step starts the next one
function step(label, callback) {
setTimeout(() => {
console.log(`${label} complete`);
callback();
}, 100);
}
step("Step 1", () => {
step("Step 2", () => {
console.log("All steps done");
});
});
console.log("Timers scheduled");Code breakdown
- Line 4
callback();greet() calls the callback only after printing Hello. greet decides the moment; the caller merely handed the function over.
- Lines 14-16
const doubled = numbers.map(function (num) {map() calls the callback five times, once per item, and builds a new array from the returned values. It is synchronous: all five calls finish before map returns.
- Line 19
const evens = numbers.filter((num) => num % 2 === 0);filter() keeps only the items for which the callback returns true. As a one-line arrow function, it returns the comparison automatically.
- Lines 23-28
function step(label, callback) {step() gives setTimeout a callback and returns immediately. Only after 100 ms does the timer callback run, and only then does it call your callback.
- Lines 30-34
step("Step 2", () => {Step 2 starts inside Step 1's callback, so it begins only after Step 1 finishes. Add more steps and this nesting keeps deepening, which is how callback hell begins.
- Line 35
console.log("Timers scheduled");This line is last in the source but runs before the timer callbacks, because asynchronous callbacks wait until the current code has finished.
Hello, Aung Kyaw!
Callback executed!
Doubled: 2,4,6,8,10
Evens: 2,4
Timers scheduled
Step 1 complete
Step 2 complete
All steps doneError-first callbacks: the Node.js convention
When an asynchronous callback fails, the caller cannot catch the error with try/catch, because the try block has already finished by then. That is why Node.js passes the error as the callback's first argument. Whoever writes the callback checks err first and returns early if it is set.
function parseAge(text, callback) {
const age = Number(text);
if (Number.isNaN(age)) {
callback(new Error(`"${text}" is not a number`));
return; // without this return, the success callback would run too
}
callback(null, age);
}
function report(err, age) {
if (err) {
console.log("Failed:", err.message);
return;
}
console.log("Age next year:", age + 1);
}
parseAge("41", report); // Age next year: 42
parseAge("forty", report); // Failed: "forty" is not a numberCallback hell: why Promises were needed
Find a user, load their orders, then read the first order's shipping status: written with callbacks, these three steps nest inside each other, and every level needs its own error check. The code grows into a pyramid that drifts to the right, nicknamed the "pyramid of doom". The next lessons show how Promises and async/await flatten the same steps so they read top to bottom.
Nested callbacks drift to the right
-----------------------------------
getUser(id, (err, user) => {
if (err) return handle(err);
getOrders(user, (err, orders) => {
if (err) return handle(err);
getShipping(orders[0], (err, status) => {
if (err) return handle(err);
show(status); // the real work is buried 3 levels deep
});
});
});In real projects
Where this shows up in real projects
On the front end, every button.addEventListener("click", handleClick) is a callback that the browser calls each time the user clicks. Most data-shaping code uses map, filter, reduce and sort with callbacks, for example products.filter(p => p.inStock).map(p => p.name). On an Express server, the route handler in app.get("/users", (req, res) => {...}) is a callback the framework calls for every request.
Most network and file work today uses Promises and async/await, yet callbacks remain essential knowledge. Older Node.js APIs such as fs.readFile, event emitters, and test frameworks with it("...", () => {...}) all take callbacks. Even a Promise's .then() accepts a callback, so understanding callbacks makes the next lessons much easier. Reading a stack trace that passes through library code also gets simpler once you know who is calling whom.
Common mistakes
Common mistakes
1. Calling the function instead of passing it
setTimeout(save(), 1000) runs save immediately and hands its result, usually undefined, to setTimeout. Write setTimeout(save, 1000). To pass arguments, wrap the call in an arrow: setTimeout(() => save(draft), 1000).
2. Forgetting to return after the error callback
If you call callback(err) without returning, execution continues and callback(null, result) runs as well. A callback that fires twice causes hard-to-find bugs such as sending two responses or saving data twice. Writing return callback(err); is the safe habit.
3. Forgetting return inside a map callback
numbers.map((n) => { n * 2; }) uses curly braces, so nothing is returned and you get [undefined, undefined, ...]. Either write return inside the braces or drop the braces: (n) => n * 2.
Best practices
Best practices
- Pull reusable callbacks out into named functions such as handleClick or formatRow; the names also show up in stack traces, which makes debugging easier.
- When you write a function that accepts a callback, call it either always synchronously or always asynchronously; mixing the two leads to unpredictable bugs.
- Once you need to chain more than two async steps, reach for Promises or async/await instead of nesting callbacks.
Mini challenge
Mini challenge: processItems with an error callback
Write processItems(items, transform, onError), which converts each item with the transform callback and reports failing items through the onError callback.
- When transform succeeds, push its result into a results array
- When transform throws, call onError(err, item) and keep processing the rest
- processItems returns the array of successful results
- Test it with a toPrice transform that turns text into a price, on a list mixing good and bad values
function processItems(items, transform, onError) {
// TODO: create a results array
// TODO: loop over items; call transform inside try/catch
// TODO: on success push the result, on failure call onError(err, item)
// TODO: return the results
}
function toPrice(text) {
// TODO: convert text to a number; throw an Error if it is NaN
}
// TODO: call processItems with ["4.5", "abc", "10", "7.25x"], toPrice
// and an onError callback that prints "Skipped: <message>"
// TODO: print the successful pricesExpected: The two bad items are skipped and the rest are shown: Skipped: bad price "abc" Skipped: bad price "7.25x" Prices: 4.5, 10 (2 of 4 items)
Show hint
Number("abc") returns NaN; test it with Number.isNaN(). Call onError inside the catch block and do not return from there, so the loop moves on to the next item.
Show solution
function processItems(items, transform, onError) {
const results = [];
for (const item of items) {
try {
results.push(transform(item));
} catch (err) {
onError(err, item);
}
}
return results;
}
function toPrice(text) {
const value = Number(text);
if (Number.isNaN(value)) throw new Error(`bad price "${text}"`);
return Math.round(value * 100) / 100;
}
const input = ["4.5", "abc", "10", "7.25x"];
const prices = processItems(input, toPrice, (err) => {
console.log("Skipped:", err.message);
});
console.log(`Prices: ${prices.join(", ")} (${prices.length} of ${input.length} items)`);Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A callback is a function passed as an argument; the receiving function decides when to call it.
- Do not confuse name (a reference) with name() (a call right now); wrap calls that need arguments in an arrow.
- map and filter callbacks are synchronous; setTimeout and event callbacks run after the current code finishes.
- Node.js uses error-first callback(err, result), and deep nesting of callbacks is why Promises appeared.
MDN — Asynchronous JavaScript — MDN Web Docs