How do you loop through arrays?

Use for...of for simple iteration, array methods (map, filter, reduce, forEach) for transformations, and a classic for loop when you need the index or early exits with full control; avoid for...in for arrays.

The options

  • for...of: reads values, supports break, continue and await. Use array.entries() to get [index, value].
  • Classic for (let i = 0; ...): full control over the index, direction and step. Fastest in hot loops, though rarely necessary.
  • forEach(fn): runs a function for each item. Cannot break, and it does not wait for async callbacks.
  • map / filter / reduce: when you are building a new value from the array. Prefer these over pushing into a result array in a loop.
  • some / every / find: stop early as soon as the answer is known.
  • for...in: iterates keys as strings, includes inherited enumerable properties and does not guarantee intent. Use it for objects, not arrays.

Async work

  • Sequential: for (const item of items) await process(item).
  • Parallel: await Promise.all(items.map(process)).
  • items.forEach(async (item) => ...) starts everything without waiting, which is a frequent bug.

Rule of thumb

If you are producing a value, use the matching array method. If you are performing side effects, especially with break or await, use for...of.

Code example

js
1const fruits = ["apple", "banana", "cherry"];
2
3for (const fruit of fruits) console.log(fruit);
4
5for (const [i, fruit] of fruits.entries()) console.log(i, fruit);
6
7for (let i = fruits.length - 1; i >= 0; i--) console.log("reverse:", fruits[i]);
8
9// Early exit
10for (const fruit of fruits) {
11 if (fruit.startsWith("b")) {
12 console.log("found", fruit);
13 break;
14 }
15}
16console.log(fruits.some((f) => f.length > 5)); // true, stops at "banana"
17
18// Building new values
19const upper = fruits.map((f) => f.toUpperCase());
20const totalChars = fruits.reduce((n, f) => n + f.length, 0);
21console.log(upper, totalChars);
22
23// Async: sequential vs parallel
24const wait = (ms, v) => new Promise((r) => setTimeout(() => r(v), ms));
25for (const f of fruits) console.log("sequential", await wait(10, f));
26console.log("parallel", await Promise.all(fruits.map((f) => wait(10, f))));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app