Higher-Order Functions
A higher-order function is a function that either
takes another function as an argument or returns a function
as its result — or both. Because JavaScript treats functions as
first-class citizens, HOFs are everywhere: built into the
language as map,
filter, and
reduce, and at the heart of every
framework, library, and modern codebase. Mastering them unlocks
functional programming, cleaner code, and fewer bugs.
map, filter, reduce, forEach,
find, sort
What Is a Higher-Order Function?
In JavaScript, functions are first-class values — they can be stored in variables, passed as arguments, and returned from other functions, just like numbers or strings. A higher-order function is any function that leverages this by either accepting a function as a parameter (callback) or returning a new function.
// ── HOF type 1: takes a function as argument ─────────────────
function applyTwice(fn, value) {
return fn(fn(value)); // calls fn twice with its own output
}
const double = x => x * 2;
console.log(applyTwice(double, 3)); // 12 (3→6→12)
console.log(applyTwice(x => x + 10, 5)); // 25 (5→15→25)
// ── HOF type 2: returns a function ───────────────────────────
function greetWith(greeting) {
return name => `${greeting}, ${name}!`; // closes over greeting
}
const sayHello = greetWith("Hello");
const sayHi = greetWith("Hi");
console.log(sayHello("Alice")); // "Hello, Alice!"
console.log(sayHi("Bob")); // "Hi, Bob!"
// ── HOF type 3: both (takes AND returns a function) ───────────
function repeat(fn, times) {
return value => {
let result = value;
for (let i = 0; i < times; i++) result = fn(result);
return result;
};
}
const quadruple = repeat(double, 2); // double twice = 4×
console.log(quadruple(5)); // 20Built-in Array HOFs
JavaScript's Array prototype
ships with a rich set of higher-order methods. They accept a callback function
and iterate over the array for you — replacing manual for
loops with declarative, readable one-liners.
true.undefined if not found.map · filter · reduce — Deep Dive
These three methods are the backbone of functional data
transformation in JavaScript. Understanding them deeply — especially
reduce — unlocks a huge range of
patterns that replace complex imperative loops with clean, composable pipelines.
const nums = [1, 2, 3, 4, 5, 6];
// ── map: transform every element ─────────────────────────────
const doubled = nums.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10, 12]
// ── filter: keep elements that pass the test ─────────────────
const evens = nums.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6]
// ── reduce: collapse to a single value ───────────────────────
const sum = nums.reduce((acc, n) => acc + n, 0);
console.log(sum); // 21
// ── Chain them: double → keep >5 → sum ───────────────────────
const result = nums
.map(n => n * 2) // [2,4,6,8,10,12]
.filter(n => n > 5) // [6,8,10,12]
.reduce((a, n) => a + n, 0); // 36
console.log(result); // 36
// ── reduce: build an object (frequency counter) ──────────────
const fruits = ["apple", "banana", "apple", "cherry", "banana", "apple"];
const freq = fruits.reduce((acc, fruit) => {
acc[fruit] = (acc[fruit] || 0) + 1;
return acc;
}, {});
console.log(freq); // { apple: 3, banana: 2, cherry: 1 }
// ── reduce: flatten a nested array ───────────────────────────
const nested = [[1,2],[3,4],[5]];
const flat = nested.reduce((acc, arr) => acc.concat(arr), []);
console.log(flat); // [1, 2, 3, 4, 5]reduce(callback, initialValue) as a
snowball rolling downhill. It starts as
initialValue, and at each step the callback merges
the current element into the accumulator. The final snowball is
your result. The acc (accumulator) can be a number,
string, array, or object — reduce can do anything.
forEach · find · findIndex · sort · every · some
Beyond the big three, JavaScript's array prototype provides several more higher-order methods for common data tasks. Each one accepts a callback and handles the iteration internally.
const users = [
{ id: 1, name: "Alice", age: 28, active: true },
{ id: 2, name: "Bob", age: 34, active: false },
{ id: 3, name: "Carol", age: 22, active: true },
];
// ── forEach: side effects only ───────────────────────────────
users.forEach(u => console.log(u.name));
// Alice Bob Carol
// ── find: first match ────────────────────────────────────────
const found = users.find(u => u.id === 2);
console.log(found.name); // "Bob"
// ── findIndex: index of first match ──────────────────────────
const idx = users.findIndex(u => u.age < 25);
console.log(idx); // 2 (Carol at index 2)
// ── every: all elements pass? ────────────────────────────────
const allAdults = users.every(u => u.age >= 18);
console.log(allAdults); // true
// ── some: at least one passes? ───────────────────────────────
const hasInactive = users.some(u => !u.active);
console.log(hasInactive); // true (Bob is inactive)
// ── sort: order by age ascending ─────────────────────────────
const byAge = [...users].sort((a, b) => a.age - b.age);
console.log(byAge.map(u => u.name)); // ["Carol", "Alice", "Bob"]
// ── sort: alphabetically by name ─────────────────────────────
const byName = [...users].sort((a, b) => a.name.localeCompare(b.name));
console.log(byName.map(u => u.name)); // ["Alice", "Bob", "Carol"]
// ── flatMap: map + flatten in one ────────────────────────────
const sentences = ["hello world", "foo bar"];
const words = sentences.flatMap(s => s.split(" "));
console.log(words); // ["hello", "world", "foo", "bar"]HOFs vs Imperative Loops
HOFs don't replace loops in all situations — but for data transformations, they produce code that is shorter, more readable, and easier to chain. Here's a side-by-side comparison of the same task written imperatively and with HOFs.
// Get discounted prices > $12
const result = [];
for (let i = 0; i < prices.length; i++) {
const discounted = prices[i] * 0.9;
if (discounted > 12) {
result.push(discounted);
}
}
// result: [22.5, 37.8, 13.5]
// Get discounted prices > $12
const result = prices
.map(p => p * 0.9)
.filter(p => p > 12);
// result: [22.5, 37.8, 13.5]
// Reads like English: "map then filter"
for or while loop when you need to:
break early (HOF chains run to completion),
mutate external state in complex ways, work with
async/await inside the iteration body, or need maximum
performance on very large arrays where the function call overhead matters.
Writing Your Own Higher-Order Functions
Building custom HOFs is how you create reusable, composable utilities tailored to your application's needs. Once you understand the pattern, you'll find yourself reaching for it constantly.
// ── Build your own map ────────────────────────────────────────
function myMap(arr, fn) {
const result = [];
for (const item of arr) result.push(fn(item));
return result;
}
console.log(myMap([1,2,3], x => x * x)); // [1, 4, 9]
// ── Build your own filter ─────────────────────────────────────
function myFilter(arr, predicate) {
const result = [];
for (const item of arr) if (predicate(item)) result.push(item);
return result;
}
console.log(myFilter([1,2,3,4,5], n => n > 3)); // [4, 5]
// ── Build your own reduce ─────────────────────────────────────
function myReduce(arr, fn, initial) {
let acc = initial;
for (const item of arr) acc = fn(acc, item);
return acc;
}
console.log(myReduce([1,2,3,4], (a,b) => a+b, 0)); // 10
// ── Pipe: run a value through a series of functions ───────────
function pipe(...fns) {
return value => fns.reduce((v, fn) => fn(v), value);
}
const process = pipe(
x => x * 2, // double
x => x + 1, // increment
x => x ** 2 // square
);
console.log(process(3)); // 49 → 3*2=6 → 6+1=7 → 7²=49
// ── Once: a function that can only be called once ─────────────
function once(fn) {
let called = false, result;
return function(...args) {
if (!called) { called = true; result = fn(...args); }
return result;
};
}
const initOnce = once(() => console.log("Initialised!"));
initOnce(); // "Initialised!"
initOnce(); // (nothing — already called)Currying & Function Composition
Currying transforms a function that takes multiple arguments into a sequence of functions each taking one argument. Function composition combines two or more functions so the output of one becomes the input of the next. Together, they are the foundation of functional programming in JavaScript.
// ── Currying: f(a, b, c) → f(a)(b)(c) ─────────────────────── function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) return fn(...args);
return (...more) => curried(...args, ...more);
};
}
const add = curry((a, b, c) => a + b + c);
console.log(add(1)(2)(3)); // 6
console.log(add(1, 2)(3)); // 6 — flexible arity
console.log(add(1)(2, 3)); // 6
// ── Practical curry: tax calculator ─────────────────────────
const addTax = rate => amount => amount * (1 + rate);
const addGST = addTax(0.18); // 18% GST
const addVAT = addTax(0.20); // 20% VAT
console.log(addGST(100)); // 118
console.log(addVAT(100)); // 120
// ── compose: right-to-left pipeline ─────────────────────────
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
// ── pipe: left-to-right pipeline ─────────────────────────────
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const double = x => x * 2;
const addOne = x => x + 1;
const square = x => x ** 2;
const transform = pipe(double, addOne, square);
console.log(transform(5)); // 121 → 10 → 11 → 121
// ── Real-world pipe: data processing ─────────────────────────
const formatUser = pipe(
u => ({ ...u, name: u.name.trim() }),
u => ({ ...u, email: u.email.toLowerCase() }),
u => ({ ...u, role: u.role || "viewer" })
);
const user = formatUser({ name: " Alice ", email: "A@B.COM" });
console.log(user); // { name:"Alice", email:"a@b.com", role:"viewer" }
Real-World HOF Patterns
These patterns built on HOFs appear in every serious JavaScript project — from React hooks to Express middleware to Node.js event systems.
// ── Debounce ────────────────────────────────────────────────── function debounce(fn, delay) let timerId; return function(...args) { clearTimeout(timerId); timerId = setTimeout(() => fn(...args), delay); }; } const onSearch = debounce(query => fetch(`/search?q=${query}`), 300); input.addEventListener("input", e => onSearch(e.target.value)); // ── Throttle ────────────────────────────────────────────────── function throttle(fn, limit) { let lastCall = 0; return function(...args) { const now = Date.now(); if (now - lastCall >= limit) { lastCall = now; return fn(...args); } }; } const onScroll = throttle(() => console.log("scrolled"), 200); window.addEventListener("scroll", onScroll); // ── Retry: async HOF ───────────────────────────────────────── function withRetry(fn, maxAttempts = 3) { return async function(...args) { for (let attempt = 1; attempt <= maxAttempts; attempt++) { try { return await fn(...args); } catch (err) { if (attempt === maxAttempts) throw err; console.log(`Attempt ${attempt} failed, retrying…`); } } };} const fetchUser = withRetry((id) => fetch(`/api/user/${id}`), 3);
Try It — Live Editor
Experiment with all the HOF methods and custom patterns in the live playground below. Modify the data and callbacks to see exactly how each one transforms the array.
Common Pitfalls & Best Practices
A few gotchas to be aware of so your HOF chains don't silently produce wrong results or hurt performance.
// ── ❌ Pitfall 1: sort mutates the original array ─────────────
const arr = [3, 1, 2];
const sorted = arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3] — original also changed!
// ✅ Fix: spread first
const sortedSafe = [...arr].sort((a, b) => a - b);
// ── ❌ Pitfall 2: missing return in reduce ────────────────────
const bad = [1,2,3].reduce((acc, n) => { acc + n; }, 0);
console.log(bad); // undefined — forgot return!
const good = [1,2,3].reduce((acc, n) => acc + n, 0); // 6
// ── ❌ Pitfall 3: chaining when a single reduce is faster ─────
// Multiple passes over large arrays can be slow
const slow = bigArray.filter(x => x.active).map(x => x.value); // 2 passes
// ✅ Use reduce for a single pass when performance matters
const fast = bigArray.reduce((acc, x) => {
if (x.active) acc.push(x.value);
return acc;
}, []);
// ── ❌ Pitfall 4: forEach for transformation ─────────────────
const results = [];
[1,2,3].forEach(n => results.push(n * 2)); // ❌ use map instead
const results2 = [1,2,3].map(n => n * 2); // ✅ cleaner
// ── ✅ Best practices ─────────────────────────────────────────
// • Use map for 1-to-1 transformation
// • Use filter for selecting a subset
// • Use reduce to collapse into any single value
// • Use forEach only for side effects (logging, DOM updates)
// • Spread before sort to avoid mutating the original array
// • Always return inside reduce callbacks
map.
Need a subset? → filter.
Need a single value? → reduce.
Need one matching element? → find.
Just need side effects? → forEach.
[1,2,3,4,5].filter(n => n % 2 === 0) return?[1,2,3].reduce((acc, n) => acc + n, 10) return?
- A higher-order function either accepts a function as an argument, returns a function, or both. This is possible because JavaScript treats functions as first-class values.
maptransforms every element and returns a new array of the same length.filterreturns a subset.reducecollapses to any single value.forEachis for side effects only — it returnsundefined. Don't use it when you need a transformed array; usemapinstead.findreturns the first match,everychecks if all elements pass,somechecks if at least one passes.sortaccepts a comparator and mutates the original array — spread first to be safe.- Currying turns
f(a, b, c)intof(a)(b)(c)— enabling partial application and reusable specialised functions. - Function composition (
pipe/compose) chains transformations declaratively, making data pipelines easy to read, test, and extend. - Real-world HOFs include debounce, throttle, memoize, retry, Express middleware, and React Higher-Order Components.
- Always spread before sort, always return inside reduce, and prefer map over forEach for transformations.
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.