Sub topic 8
Building Pipelines by Chaining Methods
This chapter assumes you already know how map, filter, and reduce work on their own: what each passes to its callback, what each returns, and why reduce needs an initial value when the array might be empty. Here the focus is on combining them. You chain the calls into a pipeline, where each step's output becomes the next step's input.
Why Chaining Works
Chaining is possible because of what each method returns. map and filter both return a new array. An array has all the array methods, so you can call another method directly on the result without storing it in a variable first.
reduce is different. It returns whatever your callback's final accumulator is: a number, a string, an object, or occasionally an array. If that value is not an array, the array chain ends there. You can still call methods that belong to the new type, such as toFixed on a number.
Here is the basic pattern:
const orders = [
{ id: 1, total: 50, status: 'paid' },
{ id: 2, total: 20, status: 'pending' },
{ id: 3, total: 80, status: 'paid' }
];
const paidRevenue = orders
.filter(order => order.status === 'paid')
.map(order => order.total)
.reduce((sum, total) => sum + total, 0);
console.log(paidRevenue); // 130Read it top to bottom. Keep the paid orders, pull out their totals, then add the totals up. Each line does one job, and the original orders array is never modified.
The diagram shows the key habit for reading or writing a chain: track the shape of the data between steps. After filter you still have order objects. After map you have numbers. After reduce you have one number. Every callback must expect the shape that the previous step produced.
Formatting a Chain
Put each method on its own line with the dot at the start of the line. This layout has three practical benefits:
- Each step reads as a separate instruction.
- You can comment out or reorder one step without touching the others.
- Diffs in version control show exactly which step changed.
Short chains of one or two calls can stay on one line. Once a chain has three or more steps, or any callback longer than a short expression, split it.
Naming the Steps
Inline arrow functions are fine for simple steps. When the logic grows, or when you reuse the same test in several places, pull the callbacks out into named functions. The chain then reads close to plain English:
const orders = [
{ id: 1, total: 50, status: 'paid' },
{ id: 2, total: 20, status: 'pending' },
{ id: 3, total: 80, status: 'paid' }
];
const isPaid = order => order.status === 'paid';
const toTotal = order => order.total;
const add = (a, b) => a + b;
const paidRevenue = orders.filter(isPaid).map(toTotal).reduce(add, 0);
console.log(paidRevenue); // 130Named callbacks can also be tested on their own. Before you pass a function by name, check how many arguments it accepts. The array method will pass it the element, the index, and the array. A function with optional extra parameters may misread the index, as the map(parseInt) pitfall covered in a later chapter shows. All three functions above use only the arguments they need, so passing them by name is safe.
A Longer Pipeline
Real pipelines often have more than three steps and use methods other than the big three. This one builds a stock report for hardware items that are actually in stock, ordered by inventory value:
const products = [
{ name: 'Keyboard', price: 80, stock: 4, category: 'hardware' },
{ name: 'Mouse', price: 25, stock: 0, category: 'hardware' },
{ name: 'IDE License', price: 120, stock: 10, category: 'software' },
{ name: 'Monitor', price: 300, stock: 2, category: 'hardware' }
];
const report = products
.filter(p => p.category === 'hardware')
.filter(p => p.stock > 0)
.map(p => ({ name: p.name, value: p.price * p.stock }))
.toSorted((a, b) => b.value - a.value)
.map(p => `${p.name}: $${p.value}`)
.join('\n');
console.log(report);
// Monitor: $600
// Keyboard: $320This example shows several things:
- Two
filtercalls in a row are allowed. You could merge them with&&, but separate filters are easier to read when each condition means something different. - The first
mapchanges the shape from product objects to{ name, value }objects. Every later step works with that new shape. toSortedreturns a new sorted array. It was added in ES2023 and is available in Node 20+ and current browsers.joinends the chain by turning the array into a string, which plays the same role here thatreduceplayed in the first example.
The mutation risk is easy to show:
const scores = [70, 95, 82];
const ranked = scores.sort((a, b) => b - a);
console.log(scores); // [95, 82, 70] (original changed)
console.log(ranked === scores); // true
const raw = [70, 95, 82];
const safeRanked = raw.slice().sort((a, b) => b - a);
console.log(raw); // [70, 95, 82] (original intact)
console.log(safeRanked); // [95, 82, 70]reverse and splice mutate the same way. Their non-mutating versions are toReversed and toSpliced.
Order of Steps Matters
You can often reorder steps and get the same result, but the cost and the correctness can change.
Filter early. Each step runs its callback once per element it receives. If you put filter before map, the map callback runs only on the elements that survived the filter. In the stock report, filtering first means the value calculation never runs for the software license or the out-of-stock mouse.
Respect shape changes. A step can only use fields that exist at that point. After .map(order => order.total) the elements are plain numbers, so a later .filter(order => order.status === 'paid') would read status from a number. That gives undefined, so the filter silently removes every element. The chain throws no error. It just returns the wrong answer.
| Placement | Callback calls in stock report | Notes |
|---|---|---|
| Filters before `map` | 4 + 3 + 2 + 2 = 11 | `map` and the formatting step see only 2 items |
| `map` before filters (keeping fields) | 4 + 4 + 4 + 2 = 14 | Value computed for items later discarded |
The numbers are small here. The principle still matters on large arrays or expensive callbacks. A later chapter on performance covers when the extra arrays a chain allocates actually matter.
Common Errors in Chains
Forgetting to return from a block body
An arrow function with braces needs an explicit return. Without it, map collects undefined for every element, and the next step receives an array of undefined values:
const doubledWrong = [1, 2, 3].map(n => { n * 2; });
console.log(doubledWrong); // [undefined, undefined, undefined]
const doubledRight = [1, 2, 3].map(n => n * 2);
console.log(doubledRight); // [2, 4, 6]When the callback returns an object literal, wrap it in parentheses: p => ({ name: p.name }). Without them, the braces are parsed as a function body.
Omitting the initial value at the end of a chain
A filter earlier in the chain can leave an empty array. A reduce without an initial value then throws:
const onlyPending = [{ id: 2, total: 20, status: 'pending' }];
try {
onlyPending
.filter(o => o.status === 'paid')
.map(o => o.total)
.reduce((sum, t) => sum + t);
} catch (err) {
console.log(err.message); // Reduce of empty array with no initial value
}
const safe = onlyPending
.filter(o => o.status === 'paid')
.map(o => o.total)
.reduce((sum, t) => sum + t, 0);
console.log(safe); // 0You might expect the input to always contain matches, but in production it eventually won't. Treat a reduce after a filter as needing an initial value.
Calling array methods after reduce
reduce usually returns a non-array, so calling .map on its result throws TypeError: ... is not a function. If you need more array steps, put them before the reduce.
Debugging a Chain
A chain has no intermediate variables to inspect. You have two simple ways to see inside one.
The first is to insert a logging step that passes values through unchanged:
const orders = [
{ id: 1, total: 50, status: 'paid' },
{ id: 2, total: 20, status: 'pending' },
{ id: 3, total: 80, status: 'paid' }
];
const peek = label => (value, index, array) => {
if (index === 0) console.log(label, array);
return value;
};
const revenue = orders
.filter(o => o.status === 'paid')
.map(peek('after filter:'))
.map(o => o.total)
.map(peek('after map:'))
.reduce((sum, t) => sum + t, 0);
// after filter: [ { id: 1, ... }, { id: 3, ... } ]
// after map: [ 50, 80 ]
console.log(revenue); // 130peek uses the third callback argument, the whole array, to log each stage once. Remove the logging steps when you are done.
The second way is to break the chain into named variables temporarily. const paid = orders.filter(...) and const totals = paid.map(...) let you set breakpoints and inspect each value in a debugger. If a chain is hard enough to debug that you keep splitting it, consider leaving it split. Well-named intermediate variables are a legitimate style.
Exercise
Given const items = [{ name: 'pen', qty: 3, price: 2 }, { name: 'book', qty: 0, price: 15 }, { name: 'bag', qty: 1, price: 40 }];, write a single chain that returns the total cost (qty × price) of items with qty greater than 0, and that returns 0 safely if no items qualify.
Show answer
items.filter(i => i.qty > 0).map(i => i.qty * i.price).reduce((sum, c) => sum + c, 0) returns 46 (6 + 40). The filter runs first so the cost is computed only for items that are kept, and the initial value 0 prevents a TypeError when the filter leaves an empty array.
Exercise
This chain returns 0 even though two orders are paid. Why? orders.map(o => o.total).filter(o => o.status === 'paid').reduce((s, t) => s + t, 0)
Show answer
After map, the elements are numbers, not order objects. o.status on a number is undefined, so the filter removes everything and reduce returns its initial value 0. Move filter before map so the predicate sees the objects that have a status field.
Exercise
A teammate writes const top3 = scores.sort((a, b) => b - a).slice(0, 3); and later finds that scores is reordered elsewhere in the program. Fix the line without changing the result.
Show answer
sort mutates scores in place. Use scores.toSorted((a, b) => b - a).slice(0, 3), or scores.slice().sort((a, b) => b - a).slice(0, 3) in environments without toSorted. Both sort a copy and leave scores untouched.