Sub topic 18
Picking the Right Loop
This chapter assumes you have read the earlier chapters on for...in, for...of, Object.entries and early exit with break. It brings those pieces together into one decision: which loop fits the task in front of you.
Start with the question you are asking
Each loop answers a different question:
- A classic
for (let i = 0; i < n; i++)loop asks "which positions?" It gives you an index you control. for...inasks "which enumerable string keys does this object have, including inherited ones?"for...ofasks "which values does this iterable produce?"Array.prototype.forEachasks "what should run for each element of this array?"
Most bugs in this area come from asking one question with a loop that answers a different one. Using for...in to get array values is the usual example.
Comparison
| Need | Classic `for` | `for...in` | `for...of` | `forEach` |
|---|---|---|---|---|
| Array values | Yes, via index | No (string keys, extra props) | Yes | Yes |
| Plain object keys | No | Yes, filter with `Object.hasOwn` | With `Object.keys` | With `Object.keys` |
| Map, Set, string, generator | No | No | Yes | Map and Set only |
| `break` / `continue` | Yes | Yes | Yes | No |
| `await` inside the body, in order | Yes | Yes | Yes | No |
| Step by 2, go backwards | Yes | No | No | No |
A decision path
Where forEach falls short
forEach ignores the promises its callback returns, and break cannot stop it. Both of these surprise people:
const ids = [1, 2, 3];
const fetchUser = id =>
new Promise(resolve => setTimeout(() => resolve(`user${id}`), 10));
async function withForEach() {
const out = [];
ids.forEach(async id => out.push(await fetchUser(id)));
return out; // returns before any push happens
}
async function withForOf() {
const out = [];
for (const id of ids) {
out.push(await fetchUser(id));
}
return out;
}
withForEach().then(r => console.log(r)); // []
withForOf().then(r => console.log(r)); // ['user1', 'user2', 'user3']Performance
On modern engines, the speed differences between these loops rarely matter outside hot paths that run millions of times. Pick the loop that states your intent clearly, and measure before you swap one for speed.
Exercise
You need to search a Map of user IDs to user objects, stop at the first user whose role is 'admin', and log that user's ID. Which loop do you use, and what does the code look like?
Show answer
Use for...of with destructuring, because a Map is iterable and you need break: for (const [id, user] of users) { if (user.role === 'admin') { console.log(id); break; } }. forEach cannot break, for...in does not iterate Map entries, and a classic for loop has no indices to use on a Map.
Exercise
Why does arr.forEach(async x => await save(x)) not wait for the saves to finish before the next line runs?
Show answer
forEach throws away each callback's return value, so it never awaits the promises the async callback returns. The loop finishes synchronously. Use for...of with await to save one at a time, or await Promise.all(arr.map(save)) to save in parallel.