Sub topic 13
Loops Without Loops: forEach, map, filter, some, and every
This chapter assumes you can write arrow functions and are comfortable with for...of, break, and truthy and falsy values from earlier chapters. Array iteration methods take a callback and run it once per element. Each method names the purpose of a common loop, so the reader can tell what the code does without tracing a counter.
The working model
Each method calls your callback with (element, index, array). The methods differ in what they do with the callback's return value:
| Method | Callback should return | Method returns | Stops early? |
|---|---|---|---|
| `forEach` | nothing (ignored) | `undefined` | No |
| `map` | the new value | new array, same length | No |
| `filter` | truthy to keep | new array, possibly shorter | No |
| `some` | truthy if it matches | `true` or `false` | Yes, on first truthy |
| `every` | truthy if it passes | `true` or `false` | Yes, on first falsy |
None of these methods change the original array.
const nums = [1, 2, 3, 4];
const evens = nums.filter((n) => n % 2 === 0);
const doubled = nums.map((n) => n * 2);
console.log(evens); // [2, 4]
console.log(doubled); // [2, 4, 6, 8]
console.log(nums.some((n) => n > 3)); // true
console.log(nums.every((n) => n > 0)); // trueChaining
Because filter and map return arrays, you can chain them. Each step reads as one sentence of intent:
const orders = [
{ id: 1, total: 120, paid: true },
{ id: 2, total: 40, paid: false },
{ id: 3, total: 75, paid: true },
];
const paidTotals = orders
.filter((order) => order.paid)
.map((order) => order.total);
console.log(paidTotals); // [120, 75]
orders.forEach((order) => {
console.log(`Order ${order.id}: ${order.total}`);
});Use forEach only for side effects such as logging or updating the DOM. If you are building a new array, use map or filter.
Common errors
Forgetting return in a block body. An arrow function with braces returns undefined unless you write return:
const wrong = [1, 2, 3].map((n) => { n * 2; });
const right = [1, 2, 3].map((n) => { return n * 2; });
console.log(wrong); // [undefined, undefined, undefined]
console.log(right); // [2, 4, 6]Trying to break out of forEach. break is a syntax error inside a callback, and return only ends the current call. If you need to stop early, use some, every, find, or a for...of loop with break.
Using map for side effects. Calling map and ignoring its result builds an array that nobody uses. Write forEach instead so the intent is clear.
When a plain loop is better
Stay with for or for...of when you need to exit early from complex logic, when you are awaiting inside the loop (covered in the next chapter), or when you are walking several arrays by index together. Use the methods when each step has a single purpose that one of them names.
Exercise
Given const words = ["apple", "", "kiwi", "banana"];, write one expression that returns the lengths of the non-empty words, and a second expression that checks whether every word is shorter than 7 characters. What do they produce?
Show answer
words.filter((w) => w).map((w) => w.length) produces [5, 4, 6]. The empty string is falsy, so filter drops it. words.every((w) => w.length < 7) produces true, because the longest word, "banana", has 6 characters.
Exercise
Why does [3, 8, 1].forEach((n) => { if (n > 5) return; console.log(n); }) print both 3 and 1?
Show answer
return ends only the current callback call, not the forEach. The callback skips 8 and keeps running for the other elements. To stop at the first value greater than 5, use some and return true there, or use a for...of loop with break.