Higher-order functions
Overview
In JavaScript, functions are values like numbers or strings — programmers say functions are first-class. You can store them in variables, put them in arrays and objects, pass them to other functions and return them.
const sayHi = () => console.log('Hi');
const actions = [sayHi, () => console.log('Bye')];
const handlers = { greet: sayHi };
actions[1](); // 'Bye'
handlers.greet(); // 'Hi'A higher-order function is one that takes a function as an argument, returns a function, or both.
Taking a function
function twice(action) {
action();
action();
}
twice(() => console.log('Hello!'));twice doesn’t know or care what the action is — it only decides how many times to run it. You’ve already used this idea with setTimeout and addEventListener.
A function passed into another function is called a callback: the higher-order function “calls it back” at the right moment.
Passing a named function
You can pass any function, not just arrow functions written in place. Pass the name without brackets — you’re handing over the function itself, not calling it:
function logRound(i) {
console.log(`Round ${i}`);
}
repeat(3, logRound); // ✓ pass the function
repeat(3, logRound()); // ✗ calls it now and passes its result (undefined)Why bother?
Higher-order functions remove repetition. Imagine three loops that differ only in what they do with each item:
for (const p of prices) console.log(p);
for (const p of prices) total += p;
for (const p of prices) if (p > 100) expensive.push(p);The looping is the same every time; only the action changes. Pull the loop into a function and pass the action in:
function each(list, action) {
for (const item of list) action(item);
}
each(prices, (p) => console.log(p));
each(prices, (p) => { total += p; });That’s exactly what the built-in forEach does.
Returning a function
function multiplier(factor) {
return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
double(5); // 10
triple(5); // 15Each returned function remembers its own factor — a closure.
Returning functions lets you configure behaviour once and reuse it:
function greaterThan(limit) {
return (n) => n > limit;
}
const prices = [120, 80, 45, 300];
prices.filter(greaterThan(100)); // [120, 300]
prices.filter(greaterThan(50)); // [120, 80, 300]Wrapping functions
A higher-order function can take a function and return a new one that adds something extra, such as logging or timing:
function withLogging(fn) {
return (...args) => {
console.log(`Calling with`, args);
const result = fn(...args);
console.log(`Result:`, result);
return result;
};
}
const add = (a, b) => a + b;
const loggedAdd = withLogging(add);
loggedAdd(2, 3); // logs the arguments and the result, returns 5The once and memoize helpers in the Closures topic are wrappers too.
Built-in examples
Arrays come with many higher-order methods:
const prices = [120, 80, 45];
prices.map((p) => p * 1.18); // add tax to each
prices.filter((p) => p > 50); // keep some
prices.some((p) => p > 100); // true
prices.every((p) => p > 10); // true
prices.find((p) => p < 100); // 80
prices.sort((a, b) => a - b); // [45, 80, 120]
prices.forEach((p) => console.log(p));Each method handles the looping; your callback says what to do with each item. You’ll study map, filter and reduce in their own topic.
Outside arrays, you’ll meet higher-order functions everywhere:
setTimeout(() => console.log('Later'), 1000);
button.addEventListener('click', handleClick);
fetch(url).then((response) => response.json());Composing functions
Small, single-purpose functions can be combined into bigger ones:
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const dashes = (s) => s.replaceAll(' ', '-');
function pipe(...fns) {
return (input) => fns.reduce((value, fn) => fn(value), input);
}
const toSlug = pipe(trim, lower, dashes);
toSlug(' Higher Order Functions '); // 'higher-order-functions'pipe takes functions and returns a function — a higher-order function in both directions.
Name your callbacks when they grow.
prices.filter(isAffordable)reads better than a five-line arrow function in the middle of a call.
Repeat an action
Write repeat(n, action) that calls action(i) for each i from 0 to n - 1. Then write not(fn) that returns a new function giving the opposite boolean of fn.
function repeat(n, action) {
// your code here
}
function not(fn) {
// your code here
}
repeat(3, (i) => console.log(`Round ${i}`));
const isOdd = not((n) => n % 2 === 0);
isOdd(3); // truefunction repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i);
}
}
function not(fn) {
return (...args) => !fn(...args);
}Summary
- Functions are values: store them, pass them, return them.
- A higher-order function takes a function as an argument or returns one.
- A function passed in is called a callback; pass it without brackets.
- They let you separate *what* to do from *how often* or *when*.
- Array methods like
map,filter,sortandforEachare higher-order functions.