Sub topic 17
Functional Style in Real Codebases: Trade-offs and Libraries
This chapter assumes you have worked through the earlier chapters. You should be comfortable with pure functions, immutable updates with spread syntax, map/filter/reduce, pipe and compose, currying, and the Maybe container. You will also need Node.js 18 or later to run the examples.
Earlier chapters covered the techniques. This one is about deciding when to use them. Functional style has real costs as well as benefits. A team that adopts it without weighing those costs can end up with code that is harder to read than the imperative version it replaced.
What Functional Style Buys You
The benefits show up most clearly in code that changes often and is shared across a team:
- Local reasoning. A pure function can be understood from its signature and body alone. You do not need to know what ran before it.
- Cheap tests. A pure function needs no mocks and no setup. You pass inputs and check outputs.
- Safe reuse. Small composable functions such as
trimorisPaidcan be reused in many pipelines without hidden coupling. - Predictable state changes. Immutable updates make change detection trivial. Frameworks like React and Redux rely on comparing references (
prev !== next) to decide what to re-render.
The Costs
Allocation and performance
Every immutable update creates a new object or array. Every step of a filter().map().reduce() chain creates an intermediate array. For a few thousand items this rarely matters. In hot loops over large datasets it can.
const orders = Array.from({ length: 1_000_000 }, (_, i) => ({
total: i % 100,
paid: i % 2 === 0
}));
console.time('chain');
const a = orders
.filter((o) => o.paid)
.map((o) => o.total)
.reduce((sum, t) => sum + t, 0);
console.timeEnd('chain');
console.time('single reduce');
const b = orders.reduce((sum, o) => (o.paid ? sum + o.total : sum), 0);
console.timeEnd('single reduce');
console.time('for loop');
let c = 0;
for (const o of orders) if (o.paid) c += o.total;
console.timeEnd('for loop');
console.log(a === b && b === c); // trueAll three versions give the same answer. The chain allocates two extra arrays, one with 500,000 objects and one with 500,000 numbers. On most machines the single reduce and the loop run noticeably faster. The local let c in the loop is mutation, but no caller can see it, so the surrounding function stays pure. That kind of contained mutation is an accepted compromise.
Shallow copies and false safety
Spread syntax and Object.freeze only work one level deep. Nested data can still be shared and mutated.
const state = Object.freeze({ user: { name: 'Ada' } });
const copy = { ...state };
copy.user.name = 'Grace'; // mutates the shared nested object
console.log(state.user.name); // Grace
const deep = structuredClone(state); // full deep copy (Node 17+, modern browsers)
deep.user.name = 'Linus';
console.log(state.user.name); // Grace (unchanged)structuredClone is safe but copies everything, which gets expensive for large trees. It also cannot clone functions or class prototypes. Libraries such as Immer solve this with structural sharing: only the changed path is copied, and untouched branches are reused.
Debugging composed code
A point-free pipeline has no intermediate variables to inspect, and stack traces show anonymous arrow functions inside reduce. A tap helper lets you look inside a pipeline without breaking it:
const pipe = (...fns) => (x) => fns.reduce((acc, fn) => fn(acc), x);
const tap = (label) => (x) => {
console.log(label, x);
return x;
};
const slugify = pipe(
(s) => s.trim(),
tap('trimmed:'),
(s) => s.toLowerCase(),
(s) => s.replace(/\s+/g, '-'),
tap('slug:')
);
slugify(' Hello Functional World ');
// trimmed: Hello Functional World
// slug: hello-functional-worldGiving pipeline steps names (const toKebab = ...) instead of inline arrows also makes stack traces readable.
Team readability
compose(map(prop('total')), filter(propEq(true, 'paid'))) is clear to someone fluent in Ramda and opaque to everyone else. Code is read far more often than it is written. Heavy point-free style and custom combinators make onboarding slower. Algebraic types such as Either and Task have the same effect when the rest of the team does not know them.
Interop with a mutable world
The DOM, Node streams, database clients, and most third-party SDKs are object-oriented and stateful. You cannot make them pure. The practical answer is the pattern from the side-effects chapter: a functional core, imperative shell.
// Functional core: pure, easy to test
const summarize = (orders) => ({
count: orders.length,
revenue: orders.filter((o) => o.paid).reduce((s, o) => s + o.total, 0)
});
// Imperative shell: all I/O lives here
async function main() {
const orders = await Promise.resolve([
{ total: 40, paid: true },
{ total: 15, paid: false }
]); // stands in for a fetch or database call
const report = summarize(orders);
console.log(JSON.stringify(report)); // {"count":2,"revenue":40}
}
main();The Library Landscape
Plain JavaScript already provides closures, higher-order functions, map/filter/reduce, spread syntax, and non-mutating methods such as toSorted, toReversed, toSpliced, and with (ES2023). Many codebases need nothing more. Libraries help when you need what the language lacks.
| Library | What it adds | Good fit | Cost |
|---|---|---|---|
| Ramda | Auto-curried, data-last utilities (`pipe`, `map`, `prop`, `evolve`) | Heavy pipeline and composition work | Learning curve; tempts teams into over-point-free code |
| lodash/fp | Curried, data-last versions of lodash functions | Teams already using lodash | Two lodash styles in one codebase cause confusion |
| Immer | Write "mutating" code on a draft; get an immutable result with structural sharing | Deeply nested state updates (Redux Toolkit uses it) | Proxy overhead; draft rules to learn |
| Immutable.js | Persistent `Map`, `List`, and other collections | Very large collections updated often | Separate API; converting to and from plain JS |
| fp-ts / Effect | Typed `Option`, `Either`, `Task`, and effect systems for TypeScript | Large TypeScript codebases with complex error handling | Steep learning curve; heavy type signatures |
Here is the same revenue calculation with Ramda (npm install ramda):
const R = require('ramda');
const orders = [
{ id: 1, total: 40, paid: true },
{ id: 2, total: 15, paid: false },
{ id: 3, total: 60, paid: true }
];
const revenue = R.pipe(
R.filter(R.propEq(true, 'paid')),
R.map(R.prop('total')),
R.sum
);
console.log(revenue(orders)); // 100And a nested update with Immer (npm install immer):
const { produce } = require('immer');
const state = { users: [{ id: 1, profile: { city: 'Lagos' } }, { id: 2, profile: { city: 'Oslo' } }] };
const next = produce(state, (draft) => {
draft.users[0].profile.city = 'Accra';
});
console.log(state.users[0].profile.city); // Lagos
console.log(next.users[0].profile.city); // Accra
console.log(state.users[1] === next.users[1]); // true (unchanged branch is shared)Deciding How Far to Go
Some guidelines for code review:
- Prefer pure functions and immutable updates by default. They cost little and pay off in tests.
- Allow mutation that callers cannot observe, such as local accumulators in a performance-critical loop.
- Use point-free style only when the function names read like a sentence. Otherwise name the argument.
- Push I/O, time, randomness, and logging to the edges of the program.
- Adopt a library to solve a problem you actually have, not to look functional.
Common Mistakes
- Treating spread as a deep copy. Nested objects are still shared.
- Chaining over huge arrays in hot paths without measuring the allocation cost.
- Mixing data-first and data-last APIs, for example native
arr.map(fn)next to Ramda'sR.map(fn, arr), in the same pipeline without a convention. - Hiding side effects inside
mapcallbacks. UseforEachor a loop when the purpose is the effect. - Converting the entire codebase at once. Start with new modules and pure business logic, where the payoff is largest.
Exercise
A teammate writes const next = { ...state }; next.settings.theme = 'dark'; return next; in a reducer, and the UI fails to re-render a component that reads state.settings. Explain why and give two fixes.
Show answer
Spread copies only the top level, so next.settings is the same object as state.settings. Assigning theme mutates the original, and a reference check prev.settings !== next.settings returns false, so the component skips re-rendering. Fix 1: copy the nested level as well, return { ...state, settings: { ...state.settings, theme: 'dark' } };. Fix 2: use Immer, return produce(state, (d) => { d.settings.theme = 'dark'; });, which copies the changed path and creates a new settings reference.
Exercise
Profiling shows that items.filter(isValid).map(toPrice).reduce(add, 0) over 2 million items is a hot spot. Rewrite it as a single pass and explain why the function stays pure even if you use a loop.
Show answer
const total = items.reduce((sum, it) => (isValid(it) ? sum + toPrice(it) : sum), 0); or a for...of loop that adds to a local let sum = 0. Both avoid the two intermediate arrays. The loop mutates only a local variable created inside the function. No caller can observe that mutation, so the same input still gives the same output with no external side effects.
Exercise
Your team is a mix of junior and senior developers on a plain JavaScript (not TypeScript) Express API. Business logic is mostly validation and data reshaping of small JSON payloads. Should you adopt fp-ts, Ramda, Immer, or none? Justify briefly.
Show answer
None, or at most Ramda for a few utilities. fp-ts targets TypeScript and has a steep learning curve. Immer helps with deeply nested state, which small request payloads rarely have. Plain pure functions, spread updates, and native array methods cover validation and reshaping, and the whole team can read them. Structure the code as a functional core (validators and transformers) and an imperative shell (Express handlers, database calls).