Chapter 13 of 49

JavaScript Callbacks & Higher-Order Functions

In the previous chapters, we learned that functions can be stored in variables, just like numbers or strings.

That small idea unlocks something very powerful: if a function is just a value, we can pass it to another function, and a function can even give back another function.

This is how JavaScript handles button clicks, timers, array processing, and data loaded from servers. The two terms behind all of this are callbacks and higher-order functions.

What is a Callback?

A callback is a function that is passed as an argument to another function, so that the other function can call it later.

Think of ordering food at a restaurant. You give the waiter your phone number and say, "Call me when my table is ready." You don't wait at the counter. The restaurant calls you back at the right time.

In code, the phone number is the function you hand over, and the restaurant is the function that decides when to call it.

function sayHello() {
    console.log("Hello!");
}

function runTwice(callback) {
    callback();
    callback();
}

runTwice(sayHello);

Output:

Hello!
Hello!

Here, sayHello is the callback. We passed it into runTwice(), and runTwice() decided to call it two times.


Functions Are Values

As we saw in the Function Expressions chapter, a function in JavaScript is a value. That means we can:

  • Store a function in a variable.

  • Pass a function as an argument to another function.

  • Return a function from another function.

Languages that allow this are said to have first-class functions. Callbacks and higher-order functions are simply the result of using functions this way.

const greet = function (name) {
    return "Hi, " + name;
};

const sameGreet = greet; // no () — we copy the function, we don't call it

console.log(sameGreet("Riya"));

Output:

Hi, Riya

Passing a Function vs Calling a Function

This is the most common beginner mistake with callbacks, so let's get it clear right away.

sayHello    → the function itself (a value you can pass around)
sayHello()  → CALLS the function and gives you its return value

When you pass a callback, you almost always want the first form:

function sayHello() {
    console.log("Hello!");
    // no return statement, so it returns undefined
}

function runTwice(callback) {
    callback();
    callback();
}

runTwice(sayHello);   // ✅ passes the function

// try...catch catches the error so we can print it and keep going (covered in the Error Handling chapter)
try {
    runTwice(sayHello()); // ❌ calls sayHello now and passes undefined
} catch (error) {
    console.log(error.message);
}

Output:

Hello!
Hello!
Hello!
callback is not a function

In the second call, sayHello() runs immediately (printing the third Hello!) and returns undefined. So runTwice() receives undefined, and trying to call undefined throws a TypeError.

Rule of thumb: when handing a function to someone else, leave off the ().


Callbacks with Arguments

The function that receives the callback can also pass data into it.

function calculate(a, b, operation) {
    return operation(a, b);
}

function add(x, y) {
    return x + y;
}

function multiply(x, y) {
    return x * y;
}

console.log(calculate(10, 5, add));
console.log(calculate(10, 5, multiply));

Output:

15
50

The calculate() function doesn't know or care what the operation is. It just calls whatever function we give it with a and b.

This makes calculate() flexible: one function, many behaviours.


Anonymous and Arrow Function Callbacks

Often a callback is used only once, so we don't bother giving it a name. We write it directly inside the function call.

function calculate(a, b, operation) {
    return operation(a, b);
}

// anonymous function expression
console.log(calculate(10, 5, function (x, y) {
    return x - y;
}));

// arrow function (the most common style today)
console.log(calculate(10, 5, (x, y) => x / y));

Output:

5
2

Arrow functions (from the previous chapter) are especially popular for callbacks because they are short.


What is a Higher-Order Function?

A higher-order function is a function that takes another function as an argument, returns a function, or does both.

So in the examples above:

Function

Role

runTwice(), calculate()

Higher-order functions (they accept a function)

sayHello, add, multiply

Callbacks (they are passed in)

The two ideas go together: a callback is what you pass, and a higher-order function is what receives it.


Functions That Return Functions

The second kind of higher-order function creates and returns a new function.

function createMultiplier(factor) {
    return function (number) {
        return number * factor;
    };
}

const double = createMultiplier(2);
const triple = createMultiplier(3);

console.log(double(5));
console.log(triple(5));

Output:

10
15

Step by step:

createMultiplier(2) → returns  function (number) { return number * 2; }
double(5)           → 5 * 2 → 10

createMultiplier(3) → returns  function (number) { return number * 3; }
triple(5)           → 5 * 3 → 15

Functions like createMultiplier() are sometimes called function factories, because they produce new functions.

You might wonder how double still remembers factor after createMultiplier() has finished running. That is a closure, and we'll explain exactly how it works in the Closures chapter, after we cover Scope and Hoisting.


Building Our Own Higher-Order Functions

Higher-order functions really shine with lists of data. Let's write a few ourselves using a simple array and the for...of loop from the Loops chapter.

Doing Something for Every Item

function forEachItem(items, action) {
    for (const item of items) {
        action(item);
    }
}

const fruits = ["Apple", "Mango", "Banana"];

forEachItem(fruits, fruit => console.log("I like " + fruit));

Output:

I like Apple
I like Mango
I like Banana

Transforming Every Item

function transform(items, change) {
    const result = [];

    for (const item of items) {
        result.push(change(item)); // push() adds an item to the end of an array
    }

    return result;
}

const prices = [100, 250, 400];
const withGst = transform(prices, price => price * 1.18);

// join() turns an array into a single string
console.log(withGst.join(", "));

Output:

118, 295, 472

Keeping Only Some Items

function keepIf(items, test) {
    const result = [];

    for (const item of items) {
        if (test(item)) {
            result.push(item);
        }
    }

    return result;
}

const marks = [35, 82, 47, 91, 28];
const passed = keepIf(marks, mark => mark >= 40);

console.log(passed.join(", "));

Output:

82, 47, 91

Notice the pattern: the loop logic is written once, inside the higher-order function. The part that changes (what to do, how to transform, what to keep) comes in as a callback.

JavaScript already has built-in versions of these: forEach(), map(), and filter(), plus reduce(), find(), sort() and more. We'll cover them properly in the Array Methods chapter. Now you know what they do under the hood.


Synchronous vs Asynchronous Callbacks

Callbacks come in two flavours.

Synchronous Callbacks

A synchronous callback runs immediately, while the higher-order function is still running. Everything we've written so far is synchronous.

console.log("Start");

function runNow(callback) {
    callback();
}

runNow(() => console.log("Callback runs"));

console.log("End");

Output:

Start
Callback runs
End

Asynchronous Callbacks

An asynchronous callback runs later, for example after a timer finishes, a file loads, or a user clicks a button. The rest of the code doesn't wait for it.

console.log("Start");

setTimeout(() => {
    console.log("Timer finished");
}, 1000);

console.log("End");

Output:

Start
End
Timer finished

"End" is printed before "Timer finished". setTimeout() only schedules the callback and returns immediately; about one second later, the callback is called.

Even with a delay of 0, a setTimeout() callback still runs after the current code has finished. Why that happens is explained in the Asynchronous JavaScript & the Event Loop chapter.


Callbacks You'll Meet Everywhere

Where

Example

When the callback runs

Timers

setTimeout(fn, 1000)

After the delay

Array methods

numbers.map(n => n * 2)

Immediately, once per item

Sorting

numbers.sort((a, b) => a - b)

Immediately, to compare items

DOM events

button.addEventListener("click", fn)

Every time the event happens

Node.js APIs

fs.readFile("a.txt", fn)

When the file has been read


Error-First Callbacks

When a task can fail, how does the callback find out? Node.js popularised a convention called the error-first callback: the first argument is an error (or null if everything went fine), and the result comes after it.

function divide(a, b, callback) {
    if (b === 0) {
        callback(new Error("Cannot divide by zero"), null);
        return;
    }

    callback(null, a / b);
}

function handleResult(error, result) {
    if (error) {
        console.log("Error: " + error.message);
    } else {
        console.log("Result: " + result);
    }
}

divide(10, 2, handleResult);
divide(10, 0, handleResult);

Output:

Result: 5
Error: Cannot divide by zero

You'll see this pattern in older Node.js code. Modern code usually uses Promises instead, which we'll cover later.


Callback Hell

Callbacks work well for one step. But when one asynchronous step depends on the previous one, the callbacks get nested inside each other:

// Each step needs the result of the previous one
getUser(userId, (user) => {
    getOrders(user, (orders) => {
        getOrderDetails(orders[0], (details) => {
            getDeliveryStatus(details, (status) => {
                console.log(status);
            });
        });
    });
});

The code keeps drifting to the right, forming a "pyramid". This is nicknamed callback hell (or the pyramid of doom). It becomes hard to read, and handling errors at every level is painful.

This exact problem is why JavaScript introduced Promises and async/await, which let us write the same steps one after another. Both have their own chapters later in this tutorial.


Common Mistakes

1. Calling the Callback Instead of Passing It

setTimeout(showMessage(), 1000); // ❌ runs showMessage right now
setTimeout(showMessage, 1000);   // ✅ runs it after 1 second

2. Forgetting to Return from the Callback

If a callback is supposed to produce a value, it must return one. With curly braces, an arrow function needs an explicit return.

function transform(items, change) {
    const result = [];
    for (const item of items) {
        result.push(change(item));
    }
    return result;
}

const wrong = transform([1, 2, 3], n => { n * 2 });        // no return!
const right = transform([1, 2, 3], n => { return n * 2; });

console.log(wrong);
console.log(right.join(", "));

Output:

[ undefined, undefined, undefined ]
2, 4, 6

(This is how Node.js prints an array. A browser console shows the same values.)

3. Ignoring the Extra Arguments a Callback Receives

A higher-order function may pass more arguments to your callback than you expect. A famous interview example uses the built-in map(), which calls its callback with (item, index, array):

const result = ["1", "2", "3"].map(parseInt);

console.log(result.join(", "));

Output:

1, NaN, NaN

Why? parseInt(string, radix) treats its second argument as the number base, and map() passes the index there:

parseInt("1", 0) → 1     (radix 0 means "use the default", base 10)
parseInt("2", 1) → NaN   (base 1 is not valid)
parseInt("3", 2) → NaN   ("3" is not a binary digit)

The fix is to control exactly what gets passed: ["1", "2", "3"].map(s => parseInt(s, 10)).


A Practical Example

Let's build a small order processor. The same processOrder() function can apply different discount rules, and reports back using callbacks for success and failure.

function processOrder(amount, applyDiscount, onSuccess, onFailure) {
    if (amount <= 0) {
        onFailure("Invalid order amount");
        return;
    }

    const finalAmount = applyDiscount(amount);
    onSuccess(finalAmount);
}

const festiveSale = amount => amount * 0.8;                       // 20% off
const flatOff = amount => (amount >= 1000 ? amount - 150 : amount); // ₹150 off on ₹1000+

const printBill = total => console.log("Amount to pay: ₹" + total);
const printError = message => console.log("Order failed: " + message);

processOrder(2500, festiveSale, printBill, printError);
processOrder(1200, flatOff, printBill, printError);
processOrder(0, flatOff, printBill, printError);

Output:

Amount to pay: ₹2000
Amount to pay: ₹1050
Order failed: Invalid order amount

Adding a new discount rule doesn't require changing processOrder() at all. We just write a new small function and pass it in.


Interview Tips

  • "What is a callback?" A function passed as an argument to another function, to be called by that function, either immediately (synchronous) or later (asynchronous).

  • "What is a higher-order function?" A function that takes a function as an argument and/or returns a function. Examples: map(), filter(), setTimeout(), addEventListener().

  • "What is callback hell and how do you avoid it?" Deeply nested asynchronous callbacks. Avoid it with named functions, Promises, and async/await.

  • Be ready to predict output order when setTimeout() is involved: synchronous code always finishes first.

Practice: write your own repeat(n, action) that calls action(i) for i from 1 to n, and a countIf(items, test) that returns how many items pass the test.

Conclusion

Because functions are values in JavaScript, we can pass them around just like data.

  • A callback is a function passed into another function to be called later.

  • A higher-order function takes a function as an argument, returns a function, or both.

  • Pass fn, not fn(), when giving away a callback.

  • Callbacks can be synchronous (run immediately) or asynchronous (run later, like setTimeout()).

  • Deeply nested asynchronous callbacks lead to callback hell, which Promises and async/await solve.

Callbacks and higher-order functions are behind array methods, events, timers, and asynchronous code, so you'll use them in almost every chapter from here on.