Sub topic 6
Looping Over Arrays with for...of and forEach
This chapter assumes you know let and const, arrow functions, and the classic for (let i = 0; ...) loop, and that you can run code in Node.js or a browser console. It also uses array destructuring from the earlier chapter.
JavaScript has two everyday ways to visit each element of an array: the for...of statement and the forEach method. They look alike, but they differ in control flow, in how they handle async code, and in how they treat empty slots.
for...of: a loop statement
for...of walks any iterable, such as arrays, strings, Sets, and Maps, and gives you each value in turn.
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// red
// green
// blueIf you need the index too, loop over entries(). It yields [index, value] pairs that you can destructure:
const colors = ['red', 'green', 'blue'];
for (const [i, color] of colors.entries()) {
console.log(`${i}: ${color}`);
}
// 0: red
// 1: green
// 2: bluefor...of is a real loop, so break, continue, and return all work as you would expect:
const readings = [12, 7, -3, 9, -1];
for (const value of readings) {
if (value < 0) {
console.log('First negative:', value); // First negative: -3
break;
}
}forEach: a method that takes a callback
forEach calls a function once for each element. It passes the element, its index, and the array itself. The next chapter covers that callback signature in detail.
const colors = ['red', 'green', 'blue'];
colors.forEach((color, i) => {
console.log(`${i}: ${color}`);
});forEach always returns undefined, so you cannot chain anything after it. You use it only for side effects such as logging, writing to the DOM, or updating outside state.
Common errors
Trying to stop forEach early
break inside a forEach callback is a syntax error. return only exits the current 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
// 4When you need to stop early, use for...of, or use a search method such as find or some, which a later chapter covers.
Expecting forEach to await
forEach ignores the promises that an async callback returns. The loop finishes immediately, and the work runs in the background with no ordering guarantee you can wait on.
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function main() {
const ids = [1, 2, 3];
ids.forEach(async id => {
await delay(100);
console.log('forEach done', id);
});
console.log('after forEach'); // prints first
for (const id of ids) {
await delay(100);
console.log('for...of done', id); // one at a time, in order
}
console.log('after for...of'); // prints last
}
main();Holes in sparse arrays
forEach skips empty slots. for...of visits them and gives you undefined. The edge cases chapter at the end of the tutorial goes into this further.
const sparse = [1, , 3];
sparse.forEach(v => console.log(v)); // 1, 3
for (const v of sparse) console.log(v); // 1, undefined, 3Choosing between them
| Need | for...of | forEach |
|---|---|---|
| Stop early with `break` | Yes | No |
| Sequential `await` | Yes | No |
| Index available | Via `entries()` | Second argument |
| Works on Sets, Maps, strings | Yes | Only on types that define it |
| Reuse a named function | Wrap it in a call | Pass it directly |
Exercise
This code is meant to print numbers until it reaches the first value greater than 10, then stop. Why does it print 3, 5, and 4 as well as 2, and how do you fix it? const nums = [2, 15, 3, 5, 4]; nums.forEach(n => { if (n > 10) return; console.log(n); });
Show answer
Inside a forEach callback, return only ends the current call, so the loop skips 15 and keeps going. Use a loop that can break: for (const n of nums) { if (n > 10) break; console.log(n); } prints only 2.
Exercise
How do you log each element of ['a', 'b'] together with its index using for...of?
Show answer
Use entries() and destructure: for (const [i, v] of ['a', 'b'].entries()) console.log(i, v); prints "0 a" and "1 b".