Sub topic 13
Loops Without Loops: forEach, map, filter, some, and every
Most loops over arrays fall into a few patterns. Some do something with each item, some build a transformed copy, some keep only matching items, and some ask a yes-or-no question about the items. JavaScript arrays have built-in methods for each of these patterns. When you use the method, the loop's purpose is in its name, and you don't manage an index variable yourself.
This chapter assumes you can write arrow functions, that you know the classic for loop and for...of from earlier chapters, and that you know how truthy and falsy values behave in a condition.
The Shared Shape: A Callback Per Element
Every method in this chapter takes a callback, which is a function the method calls once for each element. The callback receives three arguments: the element, its index, and the array itself. Most of the time you only need the first one.
const fruits = ["apple", "banana", "cherry"];
fruits.forEach((fruit, index, array) => {
console.log(index, fruit, array.length);
});
// 0 apple 3
// 1 banana 3
// 2 cherry 3The methods differ in two ways: what they do with the callback's return value, and what the method itself returns.
| Method | Uses callback's return value as | Method returns | Stops early? |
|---|---|---|---|
| `forEach` | Ignored | `undefined` | Never |
| `map` | The new element | New array, same length | Never |
| `filter` | Keep (truthy) or drop (falsy) | New array, same length or shorter | Never |
| `some` | "Does this one match?" | `true` or `false` | Yes, at the first truthy result |
| `every` | "Does this one pass?" | `true` or `false` | Yes, at the first falsy result |
forEach: Side Effects Only
forEach runs the callback for each element and throws away whatever the callback returns. Use it when the work is a side effect, such as logging, updating the DOM, or writing to an outside variable.
const prices = [4, 10, 6];
let total = 0;
prices.forEach((price) => {
total += price;
});
console.log(total); // 20forEach always returns undefined, so you can't chain another method after it. You also can't stop it partway through. break and continue are syntax errors inside the callback, because the callback is a separate function and not a loop body. A return inside the callback only ends that one call, so it behaves like continue.
[1, 2, 3, 4].forEach((n) => {
if (n === 2) return; // skips 2, does not stop the loop
console.log(n);
});
// 1
// 3
// 4map: Transform Every Element
map builds a new array. Each element of the new array is whatever the callback returned for the matching element of the original. The result always has the same length as the original, and the original array is not changed.
const celsius = [0, 25, 100];
const fahrenheit = celsius.map((c) => c * 9 / 5 + 32);
console.log(fahrenheit); // [32, 77, 212]
console.log(celsius); // [0, 25, 100]Common error: forgetting to return
An arrow function with a braced body returns undefined unless you write return. With map, that gives you an array full of undefined.
const users = [{ name: "Ada" }, { name: "Lin" }];
const broken = users.map((u) => { u.name.toUpperCase(); });
console.log(broken); // [undefined, undefined]
const fixed = users.map((u) => u.name.toUpperCase());
console.log(fixed); // ["ADA", "LIN"]To return an object literal from a concise arrow, wrap it in parentheses. Without them, JavaScript reads the braces as a function body: users.map((u) => ({ label: u.name })).
Common error: passing a function that takes extra arguments
map passes three arguments to the callback. If you pass a function directly, it receives all three, and that causes surprises when the function accepts optional parameters.
console.log(["1", "2", "3"].map(parseInt));
// [1, NaN, NaN]
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
// [1, 2, 3]parseInt treats its second argument as the radix (the number base). So the calls were parseInt("1", 0), parseInt("2", 1), and parseInt("3", 2). The last two are invalid and return NaN. Wrap the function in an arrow so that only the arguments you mean are passed.
filter: Keep What Matches
filter returns a new array with only the elements whose callback result is truthy. It applies the same truthiness rules as if, so the callback doesn't have to return an actual boolean.
const scores = [72, 95, 88, 40];
const passing = scores.filter((s) => s >= 70);
console.log(passing); // [72, 95, 88]
const mixed = [0, "hi", "", null, 42, undefined];
console.log(mixed.filter(Boolean)); // ["hi", 42]filter(Boolean) is a common idiom for removing falsy values. Be careful with it: it also removes 0 and "", which may be valid data. If you only want to drop null and undefined, say so: mixed.filter((x) => x != null). The loose != here matches both null and undefined and nothing else.
If you only need the first match and not all of them, use find. It returns the element itself, or undefined if nothing matches, and it stops searching at the first hit.
some and every: Asking Questions
some answers "does at least one element pass?" and every answers "do all elements pass?" Both stop as soon as the answer is known.
const ages = [12, 19, 25];
console.log(ages.some((a) => a < 18)); // true, stops at 12
console.log(ages.every((a) => a >= 18)); // false, stops at 12
let checks = 0;
[5, 50, 500].some((n) => {
checks++;
return n > 10;
});
console.log(checks); // 2Edge case: empty arrays
On an empty array, some returns false and every returns true, whatever the callback says. This is logically consistent: no element fails, so all of them pass. But it can let bad data through a validation check.
const cart = [];
const allInStock = cart.every((item) => item.inStock);
console.log(allInStock); // true
const canCheckout = cart.length > 0 && cart.every((item) => item.inStock);
console.log(canCheckout); // falseChaining Methods
map and filter return arrays, so you can call another method directly on the result. Read the chain top to bottom, as a sequence of steps.
const orders = [
{ id: 1, total: 120, paid: true },
{ id: 2, total: 40, paid: false },
{ id: 3, total: 75, paid: true },
];
const paidIds = orders
.filter((o) => o.paid)
.map((o) => o.id);
console.log(paidIds); // [1, 3]Put filter before map when you can, so that the transformation only runs on elements you keep. Each step creates an intermediate array. For a few thousand elements that cost doesn't matter. In a hot path over very large arrays, a single for...of loop that does both jobs at once can be faster, so measure before you rewrite.
Edge Cases Worth Knowing
Holes in sparse arrays are skipped
A sparse array has missing indexes, which are different from indexes that hold undefined. The array methods skip the holes, but for...of visits them as undefined.
const sparse = [1, , 3];
sparse.forEach((x) => console.log("forEach", x));
// forEach 1
// forEach 3
for (const x of sparse) console.log("for...of", x);
// for...of 1
// for...of undefined
// for...of 3
console.log(sparse.map((x) => x * 2).length); // 3, the hole is keptThe range is fixed when the method starts
The methods read the array's length once, before the first callback runs. Elements you push during iteration are not visited. Elements you change before they are reached are seen with their new values.
const list = [1, 2, 3];
list.forEach((x, i) => {
if (i === 0) {
list.push(99);
list[2] = 30;
}
console.log(x);
});
// 1
// 2
// 30
console.log(list); // [1, 2, 30, 99]Changing an array while you iterate over it is hard to reason about. Build a new array with map or filter instead.
Callbacks don't wait for promises
The methods call the callback and move on right away. An async callback returns a promise, and forEach ignores it. filter treats it as truthy, because every promise is an object. A later chapter covers how to run asynchronous work from a loop correctly.
When a Plain Loop Is Better
Use an array method when the method's name describes what the loop does. Use for...of or a classic for loop when:
- You need to
breakout orreturnfrom the enclosing function partway through, andfindorsomedoesn't fit the task. - You are walking two arrays in step with each other, or stepping by something other than one.
- You are iterating something that isn't an array, such as a
Map, aSet, or a generator.for...ofworks on any iterable.
Exercise
What does this code log, and why? const r = [3, 0, 7].map((n) => { if (n) return n * 10; }); console.log(r);
Show answer
It logs [30, undefined, 70]. The callback has a braced body. When n is 0, which is falsy, the if is skipped and the function ends without a return, so it returns undefined. map always keeps the original length, so that undefined becomes the second element.
Exercise
Rewrite this loop as one expression using array methods: let result = []; for (const p of products) { if (p.stock > 0) { result.push(p.name); } }
Show answer
const result = products.filter((p) => p.stock > 0).map((p) => p.name); The filter call keeps the in-stock products, then map pulls out their names. Filtering first means map only runs on products you keep.
Exercise
A form validator uses fields.every((f) => f.value !== "") to decide whether a form is complete. Under what input does it wrongly report success, and how do you fix it?
Show answer
When fields is an empty array, every returns true without calling the callback, so an empty form counts as complete. Fix it by also checking the length: fields.length > 0 && fields.every((f) => f.value !== "").
Exercise
You need to log each user until you reach one with banned: true, then stop. Why is forEach a poor fit, and what should you use instead?
Show answer
forEach can't be stopped: break is a syntax error inside its callback, and return only skips the current element. Use for (const u of users) { if (u.banned) break; console.log(u); }. You could also use users.some((u) => { if (u.banned) return true; console.log(u); return false; }), but the for...of version states the intent more clearly.