Functional Programming in JavaScript: Higher-Order Functions, Pure Functions, Currying, Composition and Memoization
Functional programming techniques in everyday JavaScript: pure functions and immutability, data pipelines with map/filter/reduce, higher-order helpers like negate, unary and tap, composition with pipe and compose, partial application, currying, and memoization with correct cache keys.
kvi5hnuCode Sprout team member7 min readOn this page
JavaScript isn't a purely functional language like Haskell, but its first-class functions and closures make functional programming (FP) techniques natural, and modern JavaScript code uses them everywhere: array pipelines, React components, Redux reducers, middleware, utility libraries. This article collects the core ideas and shows where each one helps, and where it goes too far.
Pure functions
A pure function:
- returns a result that depends only on its arguments, and
- has no side effects: it doesn't modify its arguments, global variables, the page, files or the network.
let callCount = 0;
const impureAdd = (x) => {
callCount++; // side effect: changes outside state
return x + callCount; // result depends on outside state
};
const pureAdd = (x, y) => x + y;
console.log(impureAdd(1), impureAdd(1)); // same input, different output
console.log(pureAdd(1, 2), pureAdd(1, 2));
2 3
3 3
Pure functions are easy to test (no setup, just inputs and expected outputs), easy to reason about (calling them can't break anything else), safe to cache and safe to run in parallel. Of course, programs need side effects to be useful; the FP approach is to keep most logic pure and push effects (I/O, DOM updates) to the edges.
Immutability
Pure functions don't modify their inputs; they return new values instead. Spread, map, filter, toSorted, with and structuredClone (articles 49 and 60) make this practical:
const addToCart = (cart, item) => [...cart, item];
const before = ["apple"];
const after = addToCart(before, "bread");
console.log(before, after);
[ 'apple' ] [ 'apple', 'bread' ]
Frameworks like React rely on this: they detect changes by comparing references, so mutating state in place makes updates invisible. Object.freeze can enforce immutability, but only shallowly (part 14).
Data pipelines
The most common functional pattern in JavaScript is a chain of array methods, each step a small pure transformation (articles 56–58):
const lineItems = [
{ name: "pen", price: 2, qty: 3 },
{ name: "ink", price: 8, qty: 0 },
{ name: "pad", price: 5, qty: 2 },
];
const orderTotal = lineItems
.filter((item) => item.qty > 0)
.map((item) => item.price * item.qty)
.reduce((sum, amount) => sum + amount, 0);
console.log(orderTotal);
16
Each step says what happens, not how to manage indexes and temporary variables. Statistics read similarly:
const samples = [1, 1, 3, 5, 5];
const sum = (a, b) => a + b;
const mean = samples.reduce(sum, 0) / samples.length;
const variance = samples.map((x) => (x - mean) ** 2).reduce(sum, 0) / (samples.length - 1);
console.log(mean, Math.sqrt(variance));
3 2
Higher-order functions
A higher-order function takes a function as an argument, returns one, or both. You've used built-in ones (map, filter, setTimeout) and written some (once, memoize, debounce in article 67). Small, general helpers like these can be combined in many ways:
const negate = (predicate) => (...args) => !predicate(...args);
const unary = (fn) => (arg) => fn(arg); // pass only the first argument
const tap = (fn) => (value) => { fn(value); return value; };
const isEven = (n) => n % 2 === 0;
console.log([1, 2, 3, 4].filter(negate(isEven)));
console.log(["1", "2", "3"].map(unary(parseInt))); // fixes the map(parseInt) trap
console.log([5].map(tap((v) => console.log("saw", v))));
[ 1, 3 ]
[ 1, 2, 3 ]
saw 5
[ 5 ]
negate builds the opposite of any test; unary adapts a function that would misuse extra arguments (article 56); tap lets you peek at values in a pipeline for debugging without changing them.
Composition: pipe and compose
Composing functions means feeding the output of one into the next. pipe lists the steps in the order they run; compose lists them in mathematical order, like nested calls:

const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const compose = (...fns) => (input) => fns.reduceRight((value, fn) => fn(value), input);
const trim = (s) => s.trim();
const lower = (s) => s.toLowerCase();
const dashes = (s) => s.replace(/\s+/g, "-");
const slugify = pipe(trim, lower, dashes);
console.log(slugify(" Hello Big World "));
console.log(compose(dashes, lower, trim)(" Hello Big World "));
hello-big-world
hello-big-world
Composition builds new functions out of small, tested pieces, without temporary variables. Each function must take one input and return one output for the chain to fit. A pipeline operator (value |> fn(%)) has been proposed for JavaScript, but it's still a proposal, not part of the language, so it needs a transpiler.
Partial application
Partial application fixes some of a function's arguments now and returns a function that takes the rest later. bind does this from the left (article 68), and a small helper can do it from either side:
const partial = (fn, ...first) => (...rest) => fn(...first, ...rest);
const partialRight = (fn, ...last) => (...rest) => fn(...rest, ...last);
const greet = (greeting, name) => `${greeting}, ${name}!`;
const hello = partial(greet, "Hello");
console.log(hello("Ana"));
const cubeRoot = partialRight(Math.pow, 1 / 3);
console.log(cubeRoot(27));
Hello, Ana!
3
In everyday code, an arrow function often expresses the same thing more plainly: const hello = (name) => greet("Hello", name);.
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). Hand-written curried functions are just nested arrows:
const add = (a) => (b) => a + b;
const addTax = (rate) => (price) => +(price * (1 + rate)).toFixed(2);
const addTen = add(10);
const withVat = addTax(0.2);
console.log(addTen(5), [10, 25].map(withVat));
15 [ 12, 30 ]
A generic curry helper uses the function's length to collect arguments until it has enough, accepting them one or several at a time:
function curry(fn) {
return function curried(...args) {
return args.length >= fn.length
? fn.apply(this, args)
: (...more) => curried.apply(this, [...args, ...more]);
};
}
const volume = (length, width, height) => length * width * height;
const curriedVolume = curry(volume);
console.log(curriedVolume(2)(3)(4), curriedVolume(2, 3)(4), curriedVolume(2)(3, 4));
24 24 24
Currying shines when functions are configured once and used many times, especially as callbacks: prices.map(addTax(0.2)), items.filter(hasTag("sale")). It's a common interview question ("implement curry"), and libraries like Ramda curry everything. In application code, overusing it makes stack traces and signatures harder to follow; use it where it clearly improves readability. Since it relies on length, it doesn't work with functions that use defaults or rest parameters.
Currying vs partial application: partial application fixes some arguments in one step and returns a function of the rest; currying converts a function so that it takes arguments one at a time. A curried function makes partial application trivial: curriedVolume(2) is a partial application.
Memoization
A memoized function caches results by argument, so repeated calls with the same input return immediately (article 67 showed a single-argument version). Memoization is only correct for pure functions: caching an impure one would return stale results.
For several arguments, the cache needs a key that represents all of them. A careless key creates collisions:
function memoize(fn, toKey = (...args) => JSON.stringify(args)) {
const cache = new Map();
return function (...args) {
const key = toKey(...args);
if (!cache.has(key)) cache.set(key, fn.apply(this, args));
return cache.get(key);
};
}
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
console.log(memoize(gcd)(85, 187));
const badKey = memoize((user) => user.id, (...args) => args.join("+"));
console.log(badKey({ id: 1 }), badKey({ id: 2 })); // both keys are "[object Object]"
17
1 1
The second call returned a wrong, cached answer because every object turns into "[object Object]" when joined. JSON.stringify keys work for plain data; for object arguments compared by identity, use nested Maps or a WeakMap (part 11), which also lets cached objects be garbage-collected.
To memoize a recursive function, the recursion must call the memoized version:
function memoize(fn) {
const cache = new Map();
return (n) => {
if (!cache.has(n)) cache.set(n, fn(n));
return cache.get(n);
};
}
let calls = 0;
const fib = memoize((n) => {
calls++;
return n < 2 ? n : fib(n - 1) + fib(n - 2); // calls the memoized fib
});
console.log(fib(50), calls);
12586269025 51
Without memoization, fib(50) would make over 40 billion calls; with it, each n is computed once. Unbounded caches grow forever, so production memoizers often limit their size (an LRU cache) or expire entries.
How far to go
Functional techniques make code more predictable, testable and reusable, but taken to extremes (everything curried, point-free compositions of compositions) they can make code cryptic for teammates. A balanced style that most JavaScript teams use:
- Write pure functions for business logic and keep side effects at the edges.
- Prefer non-mutating operations for shared data.
- Use array pipelines for transformations.
- Use higher-order helpers (
once,debounce,memoize, smallpipes) where they remove real repetition. - Use plain loops when control flow (early exit,
await) is clearer.
Common questions
Is JavaScript a functional language?
It's multi-paradigm: it supports functional, object-oriented and procedural styles. First-class functions and closures make FP techniques natural, but nothing forces purity or immutability the way Haskell does.
What's the difference between a higher-order function and a callback?
The higher-order function is the one that takes (or returns) a function, like map. The callback is the function passed in, like the arrow you give to map.
Do functional pipelines hurt performance?
Each map/filter step creates a new array, which costs a little. For typical data sizes it doesn't matter. For huge datasets, combine steps in one reduce or loop, or use iterator helpers (part 12), which process elements lazily without intermediate arrays.
When is memoization a bad idea?
When the function is impure, when arguments rarely repeat (the cache just consumes memory), or when computing the key costs as much as the function itself.
Summary
- Pure functions depend only on their arguments and have no side effects; they're easy to test, cache and reason about.
- Return new data instead of mutating; immutability is what frameworks like React depend on.
- Array pipelines (
filter,map,reduce) are the everyday form of FP in JavaScript. - Higher-order helpers (
negate,unary,tap,once) build behavior from small parts. piperuns functions left to right;composeright to left.- Partial application fixes some arguments; currying turns a function into a chain of single-argument functions.
- Memoize only pure functions, choose cache keys carefully, and make recursive calls go through the memoized version.
Practice Questions
Is this code pure? How would you make it pure?
const addItem = (list, x) => {
list.push(x);
return list;
}
Answer
No: it mutates its argument. A pure version returns a new array: const addItem = (list, x) => [...list, x];
What does snippet A return, and what does snippet B return?
pipe((x) => x + 1, (x) => x * 2)(5)
compose((x) => x + 1, (x) => x * 2)(5)
Answer
12 and 11. pipe adds 1 first, then doubles; compose doubles first, then adds 1.
Write a curried between(min)(max)(value) that checks whether value is in the range, and use it to filter [1, 5, 9, 12] to values from 4 to 10.
Answer
const between = (min) => (max) => (value) => value >= min && value <= max;
Then [1, 5, 9, 12].filter(between(4)(10)) gives [ 5, 9 ].
Why does memoizing with args.join(",") as the key break memoize((a, b) => a + b) for the calls f("1,2", "") and f("1", "2,")?
Answer
Both argument lists join to the key "1,2,", so the second call returns the cached result of the first ("1,2" instead of "12,"). JSON.stringify(args) produces different keys.
Review quiz
You've finished Part 8. Check your understanding of functions with the Part 8 review quiz: 25 questions on declarations and arrows, hoisting, this in every kind of call, parameters, closures, call/apply/bind and functional techniques.
Next: JavaScript Prototypes and Constructor Functions: How Classes Work Underneath

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.