๐Ÿ” JavaScript

for vs forEach vs for...of vs map โ€” Which Loop When?

๐Ÿ“… Jul 4, 2026 โฑ 3 min read

Five ways to loop, each with a personality. The decision rules:

The lineup

for (let i = 0; i < arr.length; i++)  // need the index / break early / max speed
for (const item of arr)               // clean iteration, break works โ€” DEFAULT
for (const key in obj)                // objects only (includes inherited keys!)
arr.forEach((item, i) => ...)         // callback style; no break; skips holes
const out = arr.map(x => x * 2)       // TRANSFORM โ€” returns a new array

The rules

The async trap (interview classic)

// โŒ forEach ignores await โ€” all fire at once, loop "finishes" instantly
items.forEach(async (x) => await save(x));

// โœ… sequential
for (const x of items) await save(x);

// โœ… parallel, properly awaited
await Promise.all(items.map(x => save(x)));

Full lesson: Loops.

โ† All Articles