JavaScript map, filter, and reduce
Build a transformation pipeline without mutating the source.
On this page
Arrays and arrow functions.
- Build a transformation pipeline without mutating the source.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
filter selects elements, map transforms them, and reduce combines them. Each callback receives the current element; reduce also receives the accumulator.
Provide an initial accumulator so reducing an empty array is defined. These callbacks do not mutate objects, although map and filter do not automatically deep-copy object elements.
Code example
const values = [1, 2, 3, 4];
const even = values.filter(value => value % 2 === 0);
const squares = even.map(value => value * value);
const total = squares.reduce((sum, value) => sum + value, 0);
console.log(JSON.stringify(squares));
console.log(total);
if ([].reduce((sum, value) => sum + value, 0) !== 0) throw new Error("empty");[4,16] 20
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
const values = [1, 2, 3, 4];const even = values.filter(value => value % 2 === 0);const squares = even.map(value => value * value);const total = squares.reduce((sum, value) => sum + value, 0);console.log(JSON.stringify(squares));console.log(total);if ([].reduce((sum, value) => sum + value, 0) !== 0) throw new Error("empty");Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Start with four numbers. | values = [1, 2, 3, 4] | — | |
| Keep 2 and 4. | even = [2, 4] | — | |
| Square each retained number. | squares = [4, 16] | — | |
| Accumulate 0+4, then 4+16. | total = 20 | — | |
| Serialize to deterministic JSON text. | total = 20 | [4,16] | |
| Print the total. | total = 20 | [4,16] 20 |
Behind the scenes
How JavaScript processes this code
A JavaScript engine parses and runs the source. A function body runs when the function is called. console.log writes to the console.
Cost and common mistakes
O(n) time over the pipeline and O(n) auxiliary storage for intermediate arrays.
- reduce without an initial value throws on an empty array.
- Returning an object reference from map does not clone that object.
Try it yourself
Use [1, 3, 5] as input.
Reveal answer and reasoning
squares is [] and total is 0.