Sub topic 18
Picking the Right Loop
This chapter assumes you are comfortable with let and const, arrays and objects, arrow functions, and async/await. It also builds on earlier chapters: for...in walks enumerable string keys, including inherited ones, and for...of walks the values that an iterable produces. Here we put four loops side by side: the classic for, for...in, for...of, and Array.prototype.forEach. Then we turn their differences into a decision you can make quickly.
The Four Candidates at a Glance
Each loop answers a different question.
- The classic
for (let i = 0; i < n; i++)loop answers "which positions?" You control the counter, so you control the start, the end, the step, and the direction. for...inanswers "which property names does this object have?" It gives you string keys.for...ofanswers "which values does this source produce?" It works on anything iterable.forEachanswers "what should happen to each element?" It is an array method that takes a callback.
| Feature | classic `for` | `for...in` | `for...of` | `forEach` |
|---|---|---|---|---|
| Yields | whatever you index | string keys | values | value, index, array |
| Works on | anything with indices | any object | iterables only | arrays (and a few others, such as `NodeList`) |
| Inherited keys | no | yes, if enumerable | no | no |
| `break` / `continue` | yes | yes | yes | no |
| `await` inside the body pauses the loop | yes | yes | yes | no |
| Holes in sparse arrays | visited as `undefined` | skipped | visited as `undefined` | skipped |
| Custom step or reverse order | yes | no | no | no |
Where Each Loop Fits Best
The classic for loop: when the index is the point
Use the counter loop when you need something other than "every element, front to back". Common cases are stepping by two, walking backwards, comparing neighbours, or removing items while you go.
const readings = [3, -1, 4, -1, 5, -9];
// Remove negatives in place. Walking backwards keeps the
// remaining indices valid after each splice.
for (let i = readings.length - 1; i >= 0; i--) {
if (readings[i] < 0) readings.splice(i, 1);
}
console.log(readings); // [3, 4, 5]
// Compare each element with the next one.
const temps = [10, 12, 11, 15];
for (let i = 0; i < temps.length - 1; i++) {
console.log(`${temps[i]} -> ${temps[i + 1]}`, temps[i + 1] > temps[i] ? 'up' : 'down');
}
// 10 -> 12 up
// 12 -> 11 down
// 11 -> 15 upIf you write i only to read arr[i], you probably want for...of.
for...in: when you need an object's key names
for...in still has a place: inspecting objects whose shape you don't know ahead of time, especially when you want inherited enumerable keys. That case is rare. Most of the time you want the object's own keys, and Object.keys or Object.entries with for...of gives you them without an Object.hasOwn check.
const config = { host: 'localhost', port: 8080 };
// Usually preferable: own keys only, no filter needed.
for (const [key, value] of Object.entries(config)) {
console.log(`${key}=${value}`);
}
// host=localhost
// port=8080Don't use for...in on arrays. You get string indices, extra properties, and inherited enumerable keys, as covered earlier.
for...of: the default for values
for...of is the right default for arrays, strings, Maps, Sets, generators, and DOM collections. It supports break, continue, and return, and it closes iterators properly when you exit early. With entries() you can still get the index.
const orders = [
{ id: 'a1', total: 40 },
{ id: 'b2', total: 0 },
{ id: 'c3', total: 25 },
];
for (const [i, order] of orders.entries()) {
if (order.total === 0) {
console.log(`First empty order at index ${i}: ${order.id}`);
break;
}
}
// First empty order at index 1: b2forEach: when every element gets the same side effect
forEach reads well in a chain and hands you the value, the index, and the array. Its limits come from being a callback. Inside the callback, return only ends the current call, which works like continue. You cannot break out. Throwing an exception is the only way to stop early, and that is a hack.
[1, 2, 3, 4].forEach(n => {
if (n === 2) return; // skips 2, does not stop the loop
console.log(n);
});
// 1
// 3
// 4If you need to stop early, use for...of, or a method that expresses the search directly: find, findIndex, some, or every.
Failure Modes Worth Knowing
forEach does not wait for async callbacks
This is the most common loop bug in async code. forEach ignores what the callback returns, so the promises from async callbacks are never awaited.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function withForEach(items) {
items.forEach(async item => {
await delay(10);
console.log('forEach', item);
});
console.log('forEach finished?');
}
async function withForOf(items) {
for (const item of items) {
await delay(10);
console.log('for...of', item);
}
console.log('for...of finished');
}
async function main() {
await withForEach([1, 2]);
await delay(50);
await withForOf([1, 2]);
}
main();
// forEach finished?
// forEach 1
// forEach 2
// for...of 1
// for...of 2
// for...of finishedfor...of with await runs the steps one after another. To run them in parallel and wait for all of them, use await Promise.all(items.map(async item => ...)). Don't expect forEach to do either.
Sparse arrays behave differently
Holes are array indices that were never assigned. The loops disagree about them:
const sparse = [1, , 3];
sparse.forEach(v => console.log('forEach', v));
// forEach 1
// forEach 3
for (const v of sparse) console.log('for...of', v);
// for...of 1
// for...of undefined
// for...of 3
for (const i in sparse) console.log('for...in', i);
// for...in 0
// for...in 2If your data can contain holes, decide whether you want undefined values or skipped indices, and pick the loop that matches.
Plain objects are not iterable
for (const x of {}) throws a TypeError. The fix is to choose which view of the object you want, Object.keys, Object.values, or Object.entries, rather than reaching for for...in.
A Decision Procedure
In short: use for...of by default, a counter loop when the index drives the logic, Object.entries for objects, and forEach only for simple synchronous side effects. for...in is left for the uncommon case where you need key names, inherited ones included.
Exercise
You need to send each email in an array one at a time, waiting for each send() promise before starting the next, and stop at the first failure. Which loop do you use, and why not forEach?
Show answer
Use for...of with await inside a try/catch, and break (or rethrow) on failure. forEach does not await the promises its callback returns, so all sends would start at once. It also cannot break out early, and a rejection inside its callback escapes a try/catch placed around the forEach call.
Exercise
What does this print, and which loop would you use to remove every even number from nums in place? const nums = [2, 3, 4, 6, 7]; for (let i = 0; i < nums.length; i++) { if (nums[i] % 2 === 0) nums.splice(i, 1); } console.log(nums);
Show answer
It prints [3, 6, 7]. After each splice, the next element moves into index i, and then i++ skips over it, so 4 and 6 are never checked against the removal at the right moment (4 is removed, 6 is skipped). Walk backwards instead, with for (let i = nums.length - 1; i >= 0; i--), or build a new array with nums.filter(n => n % 2 !== 0).
Exercise
Given const totals = { north: 120, south: 95 }, write a loop that logs "north: 120" and "south: 95" without using for...in.
Show answer
for (const [region, total] of Object.entries(totals)) { console.log(${region}: ${total}); } Object.entries returns an array of the object's own enumerable [key, value] pairs. That array is iterable, so for...of with destructuring walks it.