Pass the Function, Don't Call It: Callbacks in JavaScript Explained
Functions as values, what a callback is, why callbacks aren't always async, and how nesting turns into callback hell, with real output

Here's a line beginners write all the time, and what it actually does:
function greet() {
console.log("Hello!");
}
console.log("1. before");
setTimeout(greet(), 1000); // oops: the parentheses call greet right now
console.log("2. after");
1. before
Hello!
TypeError [ERR_INVALID_ARG_TYPE]: The "callback" argument must be of type function. Received undefined
"Hello!" printed immediately, and then JavaScript crashed. The parentheses in greet() don't pass the function to setTimeout. They call greet on the spot and pass along what it returned, which is undefined. One pair of parentheses is the difference between handing a function over and running it.
Here's the fixed version:
function greet() {
console.log("Hello!");
}
console.log("1. before");
setTimeout(greet, 1000); // pass the function itself
console.log("2. after");
1. before
2. after
Hello!
Without the parentheses, greet itself goes to setTimeout, which calls it a second later. That handed-over function is a callback. This post covers what callbacks are, why they exist, where you meet them, and the problem that made people look for something better. Every output is real, from Node.js 24.22, plus Chrome 157 for the event example.
Functions are values
In JavaScript, a function is a value, just like a number or a string. You can store it in a variable, put it in an array, pass it to another function, and return it from one:
function shout(text) {
return text.toUpperCase() + "!";
}
const same = shout; // stored in another variable
console.log(same("hello"));
const tools = [shout, (t) => t.length]; // stored in an array
console.log(tools[1]("hello"));
function makeGreeter(greeting) { // returned from a function
return (name) => `${greeting}, ${name}`;
}
console.log(makeGreeter("Namaste")("Asha"));
HELLO!
5
Namaste, Asha
Nothing special happened. shout and same are two names for one function, tools[1] pulled a function out of an array and called it, and makeGreeter returned a brand-new function. Everything about callbacks follows from this one fact. (If the arrow syntax is new, see function declarations vs expressions.)
What a callback is
A callback is a function you pass to another function, so that function can call it. The name says it: you give it something to call back. Here's the simplest case, with no waiting involved:
function calculate(a, b, operation) {
return operation(a, b); // call back the function we were given
}
const add = (x, y) => x + y;
const multiply = (x, y) => x * y;
console.log(calculate(4, 5, add));
console.log(calculate(4, 5, multiply));
9
20
calculate doesn't know what operation does. It calls whatever it was given. Pass add and you get 9; pass multiply and you get 20. That's the point of callbacks: the caller decides what happens, and the function decides when.
The caller passes the function in. The receiving function calls it and returns the answer.
Callbacks aren't always async
Most people meet callbacks through timers and assume a callback means waiting. It doesn't. Compare two callbacks:
console.log("A. before forEach");
[1, 2, 3].forEach((n) => console.log(" callback got", n));
console.log("B. after forEach");
setTimeout(() => console.log(" timer callback"), 0);
console.log("C. after setTimeout");
A. before forEach
callback got 1
callback got 2
callback got 3
B. after forEach
C. after setTimeout
timer callback
forEach ran its callback three times before line B: no waiting, the callback was just part of the normal flow. The timer's callback waited until the rest of the code had finished, even with a delay of 0 ms. A callback is neutral. Whether it runs now or later depends on the function that receives it. I explained the "later" case in synchronous vs asynchronous JavaScript.
Why callbacks exist in async code
Some work takes time: reading a file, asking a server, waiting for a timer. JavaScript can't stop and wait, because that would freeze everything, so instead you hand over what to do when it's done and carry on. The callback is that instruction: "when you finish, call this."
Many of Node's built-in functions follow a convention for this. The callback's first parameter is an error (or null), and the result comes second. It's called an error-first callback:
const fs = require("node:fs");
fs.writeFileSync("note.txt", "hello from a file");
fs.readFile("note.txt", "utf8", (err, data) => {
console.log("existing file:", err, "|", data);
fs.readFile("missing.txt", "utf8", (err, data) => {
console.log("missing file:", err && err.code, "|", data);
});
});
existing file: null | hello from a file
missing file: ENOENT | undefined
When the read worked, err was null and data held the contents. When the file was missing, err.code was ENOENT and there was no data. You check the error first, every time. I read the second file inside the first callback so the two lines print in a predictable order. That small move is where nesting starts.
Callbacks in common scenarios
You'll meet callbacks in four places, all shown above or below:
- Array methods like
forEach: the callback runs immediately, once per item. - Timers like
setTimeout: the callback runs later. - File and network work in Node, like
readFile: the callback runs when the work finishes, error first. - Browser events: the callback runs each time the event happens.
Here's the last one, run in Chrome's console:
const button = document.createElement("button");
button.textContent = "Add to cart";
button.addEventListener("click", () => {
console.log("callback ran: button clicked");
});
console.log("before click");
button.click();
console.log("after click");
before click
callback ran: button clicked
after click
button.click() simulates a click, so the callback ran right there. With a real user, it runs whenever they click: once, ten times, or never.
The problem with nesting
Callbacks work well for one step. The trouble starts when each step needs the result of the one before. Here's ordering a pizza: place the order, then cook it, then deliver it. Each step is asynchronous (simulated with short timers):
function placeOrder(item, callback) {
setTimeout(() => callback(null, { id: 101, item }), 50);
}
function cook(order, callback) {
setTimeout(() => callback(null, `${order.item} for order ${order.id}, cooked`), 50);
}
function deliver(food, callback) {
setTimeout(() => callback(null, `${food}, delivered`), 50);
}
placeOrder("pizza", (err, order) => {
if (err) return console.error("order failed:", err.message);
cook(order, (err, food) => {
if (err) return console.error("cooking failed:", err.message);
deliver(food, (err, result) => {
if (err) return console.error("delivery failed:", err.message);
console.log(result);
});
});
});
pizza for order 101, cooked, delivered
It works. But look at the shape: each step sits inside the previous callback, so the code drifts to the right. Every level also repeats its own if (err) check. Add a fourth step, like sending a receipt, and everything shifts again. This is callback hell, also called the "pyramid of doom".
Each step starts inside the previous callback, and every level repeats its own error check.
Callbacks themselves aren't the problem. The problem is that the order of events is stored in the indentation, which makes the code hard to read and hard to change.
Other callback problems
Trust. When you give a function your callback, you trust it to call it exactly once. If it doesn't, your code runs twice:
function buggyCharge(callback) {
callback(null, "paid");
callback(null, "paid"); // a bug: calls back twice
}
let charges = 0;
buggyCharge(() => {
charges++;
console.log("charging the card, charge #" + charges);
});
charging the card, charge #1
charging the card, charge #2
The card was charged twice. Your callback can't stop a function from calling it twice, and that bug lives in code you may not control.
Errors don't travel. An error thrown inside a callback that runs later can't be caught by a try/catch around the call that started the work. I showed that with real output in try/catch/finally in JavaScript.
These two problems, along with the pyramid, are what promises were designed to fix, and async/await makes them read like ordinary code.
When callbacks are still the right tool
Callbacks haven't gone away, and they shouldn't. Use them for event handlers, array methods and one-step jobs: a single callback, no dependent steps, no nesting. Reach for promises or async/await when steps start to depend on each other.
The takeaway: a callback is a function you pass to another function so it can call it. greet hands it over; greet() runs it. Callbacks can run immediately (forEach) or later (setTimeout, readFile), and nesting them for dependent steps is what turns into callback hell. This post stayed with the idea and skipped related tools like setInterval and util.promisify.
Look at a setTimeout or addEventListener call in your own code. Are you passing the function, or accidentally calling it?
Comments
Join the discussionNo comments yet. Be the first to comment.




