After this lesson you can take a list and turn it into another list, pick out the items you care about, or boil the list down to one number, all without writing a loop by hand. These three methods are everywhere in modern JavaScript, so it is worth getting comfortable with them.
They all take a callback: a function you hand over, which the method calls once per item. If callbacks are new to you, read callbacks and functions as values first.
map: transform every item
map calls your function on each item and collects the results into a new array of the same length.
const prices = [10, 20, 35];
const withTax = prices.map(price => price * 1.2);
console.log(withTax); // [ 12, 24, 42 ]
console.log(prices); // [ 10, 20, 35 ], unchangedThe callback receives the item, then its index, then the whole array. Most of the time you only need the item:
const names = ["asha", "ben"];
console.log(names.map((name, i) => `${i + 1}. ${name.toUpperCase()}`));
// [ '1. ASHA', '2. BEN' ]A very common use is turning data into pieces of HTML text, or pulling one property out of a list of objects: users.map(user => user.email).
Beware that map always returns a value for every item. If your function forgets to return (easy with braces), you get an array of undefined.
filter: keep some items
filter runs a test on each item. Items where the test returns a truthy value are kept; others are dropped. The result can be shorter, or empty.
const ages = [12, 17, 18, 30, 9];
const adults = ages.filter(age => age >= 18);
console.log(adults); // [ 18, 30 ]Unlike find, which stops at the first match and returns one item, filter always checks everything and returns an array.
reduce: many values into one
reduce carries an accumulator through the list. Your callback gets the accumulator so far and the current item, and returns the new accumulator. The second argument to reduce is the starting value.
const total = [5, 10, 15].reduce((sum, n) => sum + n, 0);
console.log(total); // 30Step by step: sum starts at 0; with 5 it becomes 5; with 10 it becomes 15; with 15 it becomes 30.
The result does not have to be a number. It can be an object, which makes reduce handy for counting or grouping:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const votes = ["red", "blue", "red", "green", "red", "blue"];
const counts = votes.reduce((tally, colour) => {
tally[colour] = (tally[colour] ?? 0) + 1;
return tally;
}, {});
log(JSON.stringify(counts));
</script>The page prints {"red":3,"blue":2,"green":1}. Always pass the starting value. Without it, reduce uses the first item as the accumulator, and on an empty array it throws a TypeError. Also remember to return the accumulator in every path of the callback, a classic slip.
Chaining
Because map and filter return arrays, you can call another method on the result. Read the chain top to bottom like a recipe:
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const orders = [
{ item: "pen", qty: 10, price: 2 },
{ item: "book", qty: 1, price: 12 },
{ item: "bag", qty: 2, price: 30 },
{ item: "ruler", qty: 0, price: 5 },
];
const total = orders
.filter(order => order.qty > 0) // ignore empty lines
.map(order => order.qty * order.price) // line totals
.reduce((sum, lineTotal) => sum + lineTotal, 0);
log("total:", total);
</script>The line totals are 20, 12 and 60, so the total is 92. Each step does one small job, which is easier to read and test than a loop doing everything at once. The original orders array is not changed at any point.
When a loop is better
These methods are not always the best tool.
- You need to stop early.
for...ofsupportsbreak;mapandfilteralways visit every item. - You are only doing something for its effect, such as logging or updating the page.
forEachorfor...ofsays that more honestly thanmap. - A long chain makes a reader trace the data through five steps. Naming an intermediate result with a
constoften helps.
Chaining also creates a temporary array at each step. For lists of a few thousand items that is irrelevant. Measure before worrying.
Common mistakes
- Using
mapfor side effects and ignoring the returned array. UseforEachor a loop. - A callback with braces and no
return, giving an array full ofundefined. - Forgetting the initial value in
reduce, which breaks on empty arrays and confuses the types. - Expecting
filterto change the original array. It returns a new one; assign it. - Passing a function with extra parameters by name, like
["1","2","3"].map(parseInt).mapalso passes the index, andparseInttreats it as a radix, so you get[1, NaN, NaN]. Wrap it:.map(s => parseInt(s, 10)).
Exercise
Given const words = ["tree", "sky", "mountain", "sea"], write code that keeps only words of four or more letters, makes them uppercase, and counts the total number of letters in the result using reduce.
Show one possible answer
<pre id="out"></pre>
<script>
const out = document.getElementById("out");
const log = (...parts) => { out.textContent += parts.join(" ") + "\n"; };
const words = ["tree", "sky", "mountain", "sea"];
const longWords = words.filter(w => w.length >= 4).map(w => w.toUpperCase());
const letters = longWords.reduce((sum, w) => sum + w.length, 0);
log(longWords.join(", "));
log("letters:", letters);
</script>Next: sorting arrays.
Key points
- map returns a new array of the same length, with each item transformed by your function.
- filter returns a new array holding only the items for which your function returns a truthy value.
- reduce folds an array into a single value using an accumulator, and you should always give it a starting value.
- None of the three changes the original array, so they can be chained one after another.
- Use a loop instead when the logic needs early exit or gets harder to read as a chain.