Callbacks and Higher-Order Functions
A higher-order function is a function that takes another function as an argument, returns a function, or both. A callback is a function passed to another function to be called by it, now or later. You have used both since the arrays chapter: map, filter, sort and addEventListener are higher-order functions, and the functions you pass them are callbacks. This lesson makes the idea explicit and shows the patterns built on it: composition, function factories, partial application and currying.
In One Minute
- Functions are values, so they can be passed in (callbacks) and returned (factories).
- A callback can run synchronously (
map) or later (setTimeout, event listeners). - Composition builds a pipeline from small functions:
compose(format, addTax, toCents). - A factory returns a configured function:
makeLateFee(2)returns a fee calculator with a rate of 2. - Partial application fixes some arguments now; currying turns
f(a, b, c)intof(a)(b)(c). Use them where they make code clearer, not everywhere.
Functions That Take Functions
A higher-order function lets the caller decide part of the behavior. The function supplies the structure (looping, timing, error handling), and the callback supplies the specific step:
function forEachPayment(payments, action) {
for (const p of payments) action(p);
}
function sumBy(items, getValue) {
let total = 0;
for (const item of items) total += getValue(item);
return total;
}
const payments = [{ name: "Navika", amount: 120 }, { name: "Advitha", amount: 45 }];
forEachPayment(payments, (p) => console.log(`${p.name}: $${p.amount}`));
console.log(sumBy(payments, (p) => p.amount));
console.log(sumBy(payments, (p) => p.name.length));Navika: $120
Advitha: $45
165
13sumBy doesn't know or care what it is summing; the callback decides. One function now covers "total amount", "total characters", "total of anything".
Synchronous vs Asynchronous Callbacks
| Callback | When it runs | Examples |
|---|---|---|
| Synchronous | Before the higher-order function returns | map, filter, sort, forEach, reduce |
| Asynchronous | Later, after the current code finishes | setTimeout, addEventListener, then on a promise |
console.log("start");
[1, 2].forEach((n) => console.log("sync callback", n));
setTimeout(() => console.log("async callback"), 0);
console.log("end");start
sync callback 1
sync callback 2
end
async callbackKnowing which kind you're dealing with matters: a value computed in an asynchronous callback isn't available on the next line. The async chapter is built on this distinction.
Functions That Return Functions
A function factory creates and returns a new function, configured by its arguments. The returned function remembers those arguments through a closure (the next lesson explains how):
function makeLateFee(ratePerDay, cap) {
return (daysLate) => Math.min(daysLate * ratePerDay, cap);
}
const standardFee = makeLateFee(2, 30);
const strictFee = makeLateFee(5, 100);
console.log(standardFee(12), strictFee(12));
console.log(standardFee(40), strictFee(40));
function makeFormatter(currency) {
const fmt = new Intl.NumberFormat("en-US", { style: "currency", currency });
return (amount) => fmt.format(amount);
}
const usd = makeFormatter("USD");
console.log(usd(1234.5));24 60
30 100
$1,234.50makeFormatter creates the expensive Intl.NumberFormat object once, and every call to the returned function reuses it.
Composition
Function composition combines small functions into a bigger one, where the output of each becomes the input of the next. A small pipe helper applies functions left to right:
const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const toCents = (dollars) => Math.round(dollars * 100);
const addTax = (cents) => Math.round(cents * 1.0825);
const formatCents = (cents) => `$${(cents / 100).toFixed(2)}`;
const priceWithTax = pipe(toCents, addTax, formatCents);
console.log(priceWithTax(120));
console.log(priceWithTax(19.99));$129.90
$21.64Each step is tiny, named and testable on its own; the pipeline reads as a description of the process. (8.25% is the combined sales tax rate in Dallas.) compose is the same idea applied right to left, matching mathematical notation f(g(x)).
Partial Application
Partial application fixes some of a function's arguments now, producing a function that takes the rest later. bind can do it, or a small helper:
const partial = (fn, ...fixed) => (...rest) => fn(...fixed, ...rest);
function feeLine(currency, name, amount) {
return `${name}: ${amount} ${currency}`;
}
const usdLine = partial(feeLine, "USD");
console.log(usdLine("Navika", 120));
const navikaLine = partial(feeLine, "USD", "Navika");
console.log(navikaLine(60));
const bound = feeLine.bind(null, "USD", "Srihitha");
console.log(bound(85));Navika: 120 USD
Navika: 60 USD
Srihitha: 85 USDPartial application is handy for adapting a general function to a callback slot: amounts.map(partial(feeLine, "USD", "Navika")).
Currying
Currying transforms a function of several arguments into a chain of functions that each take one argument: f(a, b, c) becomes f(a)(b)(c). Each call returns a function waiting for the next argument:
const lateFee = (rate) => (cap) => (days) => Math.min(days * rate, cap);
console.log(lateFee(2)(30)(12));
const twoDollarRate = lateFee(2);
const standard = twoDollarRate(30);
console.log([5, 12, 40].map(standard));
function curry(fn) {
return function curried(...args) {
return args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);
};
}
const curriedAdd = curry((a, b, c) => a + b + c);
console.log(curriedAdd(1)(2)(3), curriedAdd(1, 2)(3), curriedAdd(1, 2, 3));24
[10, 24, 30]
6 6 6The generic curry helper uses fn.length (the number of declared parameters) to know when it has enough arguments. Libraries in the functional programming style (Ramda, lodash/fp) curry everything; everyday JavaScript mostly uses factories and partial application instead.
Common Higher-Order Helpers
Some higher-order functions are used so often they have standard names (you'll implement several in interview questions):
| Helper | Does |
|---|---|
once(fn) | Returns a function that runs fn only the first time |
memoize(fn) | Caches results by argument, so repeated calls are instant |
debounce(fn, ms) | Runs fn only after calls stop for ms milliseconds |
throttle(fn, ms) | Runs fn at most once every ms milliseconds |
retry(fn, times) | Calls an async fn again when it fails |
function once(fn) {
let done = false;
let result;
return (...args) => {
if (!done) {
done = true;
result = fn(...args);
}
return result;
};
}
function memoize(fn) {
const cache = new Map();
return (arg) => cache.getOrInsertComputed(arg, fn);
}
const sendWelcome = once((name) => `Welcome email sent to ${name}`);
console.log(sendWelcome("Navika"), "|", sendWelcome("Advitha"));
let computed = 0;
const slowSquare = memoize((n) => { computed++; return n * n; });
console.log(slowSquare(12), slowSquare(12), slowSquare(5), "computed:", computed);Welcome email sent to Navika | Welcome email sent to Navika
144 144 25 computed: 2memoize uses the ES2026 Map.prototype.getOrInsertComputed, which calls fn only for arguments it hasn't seen.
In Practice
The Fee Tracker's report builder is a higher-order function: it takes the steps (filter, value, format) as functions, so one builder produces many reports:
function buildReport(rows, { where = () => true, value, format = String, title }) {
const selected = rows.filter(where);
const total = selected.reduce((sum, row) => sum + value(row), 0);
return `${title}: ${format(total)} (${selected.length} rows)`;
}
const usd = (n) => new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(n);
const payments = [
{ name: "Navika", grade: 9, amount: 120, late: false },
{ name: "Srihitha", grade: 11, amount: 85, late: true },
{ name: "Advitha", grade: 9, amount: 45, late: true },
];
console.log(buildReport(payments, { title: "All payments", value: (p) => p.amount, format: usd }));
console.log(buildReport(payments, { title: "Late payments", where: (p) => p.late, value: (p) => p.amount, format: usd }));
console.log(buildReport(payments, { title: "Grade 9 students", where: (p) => p.grade === 9, value: () => 1 }));All payments: $250.00 (3 rows)
Late payments: $130.00 (2 rows)
Grade 9 students: 2 (2 rows)Common Mistakes
Calling the callback instead of passing it. list.map(format()) passes format's result. Pass format.
Passing a function with extra parameters. ["1", "2"].map(parseInt) passes the index as the radix. Wrap it: .map((s) => parseInt(s, 10)).
Losing this when passing a method. list.forEach(obj.method) calls it without obj. Use (x) => obj.method(x).
Overusing currying and point-free style. Clever chains can hide what the code does. Optimize for the reader.
Interview Corner
What is a higher-order function?
A function that takes a function as an argument or returns a function. map, filter, reduce, setTimeout and addEventListener take functions; factories such as bind, debounce and memoize return them. They let behavior be passed around as data.
What is the difference between currying and partial application?
Currying converts an n-argument function into n nested one-argument functions, f(a)(b)(c). Partial application fixes some arguments of a function and returns a function taking the remaining ones, in any grouping, partial(f, a)(b, c). Function.prototype.bind performs partial application.
Implement pipe.
Show solution
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const double = (n) => n * 2;
const inc = (n) => n + 1;
console.log(pipe(double, inc)(5), pipe(inc, double)(5));11 12Order matters: double then increment gives 11; increment then double gives 12.
Practice
Challenge: Write makeCounter({ start, step }) that returns an object with next() and reset() functions, using a factory and closures (no classes).
Show solution
function makeCounter({ start = 0, step = 1 } = {}) {
let value = start;
return {
next: () => (value += step),
reset: () => { value = start; },
};
}
const receipts = makeCounter({ start: 100, step: 10 });
console.log(receipts.next(), receipts.next());
receipts.reset();
console.log(receipts.next());110 120
110Key Takeaways
| Pattern | Example |
|---|---|
| Callback | list.filter((p) => p.late) |
| Factory | const fee = makeLateFee(2, 30) |
| Composition | pipe(toCents, addTax, format)(120) |
| Partial application | feeLine.bind(null, "USD") |
| Currying | rate => cap => days => ... |
| Memoize | cache.getOrInsertComputed(arg, fn) |
Was this tutorial helpful?