Sub topic 6
Looping Over Arrays with for...of and forEach
Most array work comes down to visiting each element in turn. JavaScript gives you several ways to do it, and they behave differently on four points: whether you can stop early, how they handle await, what they do with empty slots, and what happens if the array changes while you loop. This chapter covers the two loops you will use most, for...of and forEach, and compares them with the classic indexed for loop.
This chapter assumes you know let and const, arrow functions, the basic for loop, and how to read elements by index. Callbacks get a full treatment in the next chapter. Here you only need to know that forEach calls a function you give it once per element.
The Three Common Loops
Here is the same task written three ways: print each fruit with its position.
const fruits = ['apple', 'banana', 'cherry'];
// 1. Classic indexed for loop
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}
// 2. for...of with entries() for the index
for (const [i, fruit] of fruits.entries()) {
console.log(i, fruit);
}
// 3. forEach with a callback
fruits.forEach((fruit, i) => {
console.log(i, fruit);
});All three print 0 apple, 1 banana, 2 cherry. The differences show up in less tidy situations.
for...of
for...of works on any iterable. An iterable is an object that can hand out its values one at a time, and arrays, strings, Map, Set, and NodeList all qualify. On each pass the loop variable holds the next value, not the index.
const scores = [72, 88, 95];
let total = 0;
for (const score of scores) {
total += score;
}
console.log(total); // 255You can use const for the loop variable because each pass creates a new binding. When you also need the index, loop over array.entries() and destructure each [index, value] pair, as in the first example.
forEach
forEach is a method on the array. It calls your callback once per element with three arguments: the element, its index, and the array. It always returns undefined, so it is only useful for side effects such as logging, writing to the DOM, or updating outside variables.
const prices = [10, 20, 30];
const result = prices.forEach(p => console.log(p * 2));
console.log(result); // undefinedIf you catch yourself pushing into a new array from inside forEach, you probably want map or filter, which later chapters cover.
The classic for loop
The indexed for loop is the most flexible. You control the start, the end, and the step, so you can loop backward, skip every other element, or compare arr[i] with arr[i + 1]. The cost is more syntax and more room for off-by-one errors, such as writing i <= arr.length.
const steps = ['a', 'b', 'c', 'd', 'e'];
for (let i = steps.length - 1; i >= 0; i -= 2) {
console.log(steps[i]); // 'e', 'c', 'a'
}Stopping Early: break, continue, and return
This is the biggest practical difference. for...of and for support break and continue. forEach supports neither.
const temps = [18, 21, -999, 25, 19];
for (const t of temps) {
if (t === -999) break; // sensor error: stop reading
if (t < 20) continue; // skip cool readings
console.log(t); // 21
}Inside a forEach callback, break is a syntax error. return only ends the current call, and forEach moves on to the next element, so it acts like continue:
[1, 2, 3, 4].forEach(n => {
if (n === 2) return; // skips 2, does NOT stop the loop
console.log(n); // 1, 3, 4
});Loops and async/await
forEach does not wait for promises. If the callback is async, forEach starts every call right away, ignores the promises they return, and finishes before any of the work completes.
const delay = (ms, value) =>
new Promise(resolve => setTimeout(() => resolve(value), ms));
async function withForEach() {
const ids = [3, 1, 2];
ids.forEach(async id => {
const v = await delay(id * 100, id);
console.log('forEach got', v);
});
console.log('forEach finished'); // prints FIRST
}
async function withForOf() {
const ids = [3, 1, 2];
for (const id of ids) {
const v = await delay(id * 100, id);
console.log('for...of got', v);
}
console.log('for...of finished'); // prints LAST
}
withForEach().then(() => new Promise(r => setTimeout(r, 400))).then(withForOf);The forEach version prints forEach finished first, then the values in the order 1, 2, 3 as their timers fire. The for...of version waits on each step and prints 3, 1, 2, then for...of finished.
If you want the operations to run in parallel and still wait for all of them, use await Promise.all(ids.map(id => delay(id * 100, id))).
Empty Slots in Sparse Arrays
A sparse array has holes, meaning indexes with no element at all. That is different from holding undefined. The loops treat holes differently:
const sparse = [1, , 3]; // index 1 is a hole
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: 3forEach skips holes. for...of and the indexed for loop visit every index up to length and read undefined from holes. Sparse arrays are rare in well-written code, and the Edge Cases chapter covers them in more detail. Just keep in mind that the two loops can see different numbers of elements.
Changing the Array While Looping
Changing an array while you loop over it is a common source of bugs, and the two loops react differently.
forEach fixes the range of indexes before the first call. Elements you push during the loop are not visited. Elements you remove before they are reached are skipped, and the ones after them shift down.
The array iterator behind for...of reads length again on every step. Elements you push are visited, so pushing on every pass never ends:
const queue = ['a'];
for (const item of queue) {
console.log(item);
if (queue.length < 3) queue.push(item + '!'); // guard prevents an infinite loop
}
// a, a!, a!!This can be useful for a work queue, but it is usually an accident. Removing items during a loop is worse in both styles:
const nums = [1, 2, 2, 3];
nums.forEach((n, i) => {
if (n === 2) nums.splice(i, 1);
});
console.log(nums); // [1, 2, 3] the second 2 was skippedAfter the first 2 is removed, the second 2 moves into index 1, which has already been visited. Fix this by building a new array with filter, or by looping backward with a classic for loop so that removals only shift elements you have already handled.
Avoid for...in on Arrays
for...in walks over an object's enumerable property keys. On an array it gives you indexes as strings ('0', '1'), it includes any extra properties added to the array, and the spec did not guarantee its order in older engines. Use for...of for values and entries() when you need indexes.
Comparison Table
| Feature | for (i) | for...of | forEach |
|---|---|---|---|
| `break` / `continue` | Yes | Yes | No |
| Waits for `await` | Yes | Yes | No |
| Index available | Yes | Via `entries()` | Second argument |
| Works on any iterable | No (needs index access) | Yes | Arrays, plus `Map`, `Set`, `NodeList` methods |
| Holes in sparse arrays | Visited as `undefined` | Visited as `undefined` | Skipped |
| Elements pushed during loop | Visited if the condition rereads `length` | Visited | Not visited |
| Return value | n/a | n/a | `undefined` |
On performance, the differences are small in modern engines. Choose based on behaviour and readability, and only reach for a classic for loop for speed after profiling shows the loop is a bottleneck.
Exercise
The function below should return true as soon as it finds a negative number, but it always returns false. Explain why and rewrite it with for...of. function hasNegative(nums) { nums.forEach(n => { if (n < 0) return true; }); return false; }
Show answer
The return true exits only the arrow callback, not hasNegative. forEach ignores the callback's return value and keeps going, so the outer function always reaches return false. Rewrite: function hasNegative(nums) { for (const n of nums) { if (n < 0) return true; } return false; } Here return exits hasNegative directly. The idiomatic one-liner is nums.some(n => n < 0).
Exercise
Given const files = ['a.txt', 'b.txt'] and an async function upload(name) that returns a promise, write code that uploads the files one at a time, in order, and logs 'done' only after both finish.
Show answer
async function uploadAll() { for (const name of files) { await upload(name); } console.log('done'); } A forEach with an async callback would log 'done' immediately and start both uploads at once, because forEach does not wait for the promises the callback returns.
Exercise
What does this print, and why? const arr = [1, , 3]; let count = 0; arr.forEach(() => count++); for (const _ of arr) count++; console.log(count);
Show answer
It prints 5. forEach skips the hole at index 1, so it runs twice. for...of visits all three indexes and reads undefined for the hole, so it runs three times. 2 + 3 = 5.