Intermediate · 9 of 17 · 17 min read
Higher-order functions
Functions that take or return functions, the array methods built on them, and the composition, currying and memoising patterns they make possible.
- Higher-order functions
A higher-order function either takes a function as an argument or returns a function — or both. That is the whole definition. It is possible because functions in JavaScript are ordinary values: assignable, passable, returnable.
Functions are values
const greet = function (name) { return `Hello, ${name}`; }; // in a variable
const handlers = [greet]; // in an array
const config = { onGreet: greet }; // in an object
console.log(handlers[0]('Ana')); // "Hello, Ana"
console.log(config.onGreet('Beto')); // "Hello, Beto"
console.log(typeof greet); // "function"
console.log(greet.name, greet.length); // "greet" 1 — functions are objects too
Taking a function
The caller supplies the behaviour, and your function supplies the structure:
function processUserInput(callback) {
const name = 'Gabriel'; // in real life, read from somewhere
return callback(name);
}
console.log(processUserInput((n) => `Hello, ${n}!`)); // "Hello, Gabriel!"
console.log(processUserInput((n) => n.toUpperCase())); // "GABRIEL"
This is what every array method does. The method owns the iteration; you own the decision:
const people = [
{ name: 'Ana', age: 21 },
{ name: 'Beto', age: 17 },
{ name: 'Caro', age: 34 },
];
console.log(people.map((p) => p.name)); // ["Ana", "Beto", "Caro"]
console.log(people.filter((p) => p.age >= 18).length); // 2
console.log(people.reduce((sum, p) => sum + p.age, 0)); // 72
console.log(people.some((p) => p.age < 18)); // true
console.log(people.every((p) => p.age > 10)); // true
console.log(people.find((p) => p.age > 30).name); // "Caro"
console.log([...people].sort((a, b) => a.age - b.age)[0].name); // "Beto"
Which to reach for, on one line each:
| Goal | Method |
|---|---|
| Same length, each item transformed | map |
| Fewer items, each one unchanged | filter |
| One value out of many | reduce |
| The first match, or its index | find / findIndex |
| A yes/no answer about the whole array | some / every |
| A new order | toSorted, or sort on a copy |
The imperative version and the declarative version of the same job, for contrast:
const nums = [1, 2, 3, 4, 5, 6];
const evensLoop = [];
for (let i = 0; i < nums.length; i++) {
if (nums[i] % 2 === 0) evensLoop.push(nums[i] * 10);
}
const evensHof = nums.filter((n) => n % 2 === 0).map((n) => n * 10);
console.log(evensLoop, evensHof); // [20, 40, 60] [20, 40, 60]
The loop says how; the chain says what. The chain also has no index variable to get wrong.
reduce, properly
reduce is the general one — map and filter can both be written with it. The signature is
(accumulator, item, index, array) plus an initial value, and always pass the initial value:
const nums = [1, 2, 3, 4];
console.log(nums.reduce((total, n) => total + n, 0)); // 10
console.log(nums.reduce((max, n) => (n > max ? n : max), -Infinity)); // 4
// map and filter, as reduces — to show reduce is the primitive
console.log(nums.reduce((out, n) => [...out, n * 2], [])); // [2, 4, 6, 8]
console.log(nums.reduce((out, n) => (n % 2 ? [...out, n] : out), [])); // [1, 3]
The accumulator does not have to be a number. Counting and grouping are the two patterns worth memorising, because they come up in interviews constantly:
const words = ['a', 'b', 'a', 'c', 'a'];
const counts = words.reduce((acc, word) => {
acc[word] = (acc[word] ?? 0) + 1;
return acc;
}, {});
console.log(counts); // { a: 3, b: 1, c: 1 }
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Bob', age: 21 },
{ name: 'Charlie', age: 23 },
];
const byAge = people.reduce((acc, person) => {
(acc[person.age] ??= []).push(person);
return acc;
}, {});
console.log(Object.keys(byAge)); // ["21", "23"]
console.log(byAge[21].length); // 2
// The modern built-in, when your runtime has it:
console.log(Object.keys(Object.groupBy(people, (p) => p.age))); // ["21", "23"]
Returning a function
The other half of the definition, and where closures come in — the returned function remembers the arguments of the call that created it.
function multiplier(factor) {
return (n) => n * factor; // `factor` is captured
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(5), triple(5)); // 10 15
once
Runs the wrapped function one time and returns the stored result afterwards:
function once(fn) {
let called = false;
let result;
return (...args) => {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
const init = once(() => {
console.log('initialising');
return 42;
});
console.log(init(), init(), init()); // "initialising" logged once, then 42 42 42
memoize
Same idea, keyed by the arguments:
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (!cache.has(key)) cache.set(key, fn(...args));
return cache.get(key);
};
}
let calls = 0;
const slowSquare = memoize((n) => {
calls += 1;
return n * n;
});
console.log(slowSquare(4), slowSquare(4), calls); // 16 16 1
JSON.stringify as the key is the usual compromise: fine for primitives, wrong for functions and
for objects whose key order differs. For a single object argument, a WeakMap keyed by the object
itself is both faster and leak-free.
debounce and throttle
The two that come up whenever an interview mentions scroll or search-as-you-type:
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer); // every call cancels the pending one
timer = setTimeout(() => fn(...args), wait);
};
}
function throttle(fn, interval) {
let last = 0;
return (...args) => {
const now = Date.now();
if (now - last >= interval) { // ignore calls inside the window
last = now;
fn(...args);
}
};
}
const search = debounce((q) => console.log('searching', q), 300);
search('a'); search('ab'); search('abc'); // only "searching abc", 300ms after the last call
Debounce waits for the storm to end — one call at the end. Throttle lets one through per interval — calls at a fixed maximum rate.
compose and pipe
Combining small functions into one:
const pipe = (...fns) => (value) => fns.reduce((acc, fn) => fn(acc), value);
const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);
const add1 = (n) => n + 1;
const double = (n) => n * 2;
console.log(pipe(add1, double)(5)); // 12 — add first, then double
console.log(compose(add1, double)(5)); // 11 — double first, right to left
pipe reads in the order the steps happen, which is why it is usually the one to prefer.
Currying
Turning a function of several arguments into a chain of one-argument functions:
const curriedAdd = (a) => (b) => (c) => a + b + c;
console.log(curriedAdd(1)(2)(3)); // 6
const add10 = curriedAdd(10);
const add10and20 = add10(20);
console.log(add10and20(5)); // 35 — each step is reusable
This is what makes partial application natural: every intermediate step is a usable function.
Common mistakes
Passing a method reference and losing this
Mistake. items.map(this.format).
Why it fails. Only the function is passed, so the receiver is gone and this is undefined.
What to do instead. items.map((item) => this.format(item)), or bind it.
A callback with a wrong-arity argument
Mistake. ['1', '2', '3'].map(parseInt).
Why it fails. map passes (value, index, array), and parseInt reads the second argument as
the radix — so the second call is parseInt('2', 1), which is NaN.
What to do instead. Pass only what you mean: .map((s) => parseInt(s, 10)), or .map(Number).
console.log(['1', '2', '3'].map(parseInt)); // [1, NaN, NaN]
console.log(['1', '2', '3'].map((s) => parseInt(s, 10))); // [1, 2, 3]
Spreading inside a reduce
Mistake. arr.reduce((out, x) => [...out, f(x)], []).
Why it fails. Each step copies the whole accumulator, making the reduce O(n²) — noticeable from a
few thousand items.
What to do instead. push into the accumulator and return it, or just use map.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
What makes a function a higher-order function?
What is currying?
What is the difference between debouncing and throttling a function?
Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.