Iteration
JavaScript · Reference cheat sheet
Iteration
JavaScript · Reference cheat sheet
📋 Overview
JavaScript offers several iteration styles: index for, for...of, for...in, while, array methods, and iterators/generators. Choose based on whether you need indices, early exit, async, or transformation pipelines.
🔧 Core concepts
- Indexed
for: full control of index and step. for...of: values from iterables.for...in: enumerable keys (objects) — rarely for arrays.- Array methods:
forEach,map,filter,reduce— functional pipelines;forEachcannotbreak. while/do...while: condition-driven loops.- Async:
for await...of, orPromise.allover mapped async work.
for (let i = 0; i < arr.length; i++) {
/* index + value: arr[i] */
}💡 Examples
const arr = ["a", "b", "c"];
// Indices + values
for (const [i, v] of arr.entries()) {
console.log(i, v);
}
// Object keys / values / entries
const obj = { x: 1, y: 2 };
for (const key of Object.keys(obj)) console.log(key);
for (const val of Object.values(obj)) console.log(val);
for (const [k, v] of Object.entries(obj)) console.log(k, v);
// Pipeline
const sum = arr
.map((s) => s.toUpperCase())
.filter((s) => s !== "B")
.reduce((acc, s) => acc + s.length, 0);
// forEach (no break)
arr.forEach((v, i) => console.log(i, v));
// Early exit → for...of
for (const v of arr) {
if (v === "b") break;
}
// Nested with labeled break
outer: for (const row of matrix) {
for (const cell of row) {
if (cell < 0) break outer;
}
}// Async sequential
for (const url of urls) {
await fetch(url);
}
// Async parallel
await Promise.all(urls.map((u) => fetch(u)));
// Generator-driven
function* walk(node) {
yield node;
for (const child of node.children ?? []) yield* walk(child);
}⚠️ Pitfalls
forEachignoresasynccallbacks’ promises and cannot break.for...inon arrays includes enumerable extras and yields string keys.- Mutating length while iterating with index
forneeds care. - Prefer
Object.keys/entriesoverfor...infor own properties.
🔗 Related
- for_of.md — for...of details
- while.md — while loops
- iterator.md — iterators & generators
- arrays.md — map/filter/reduce
- objects.md — key enumeration
- async.md — async iteration
- map.md — Map iteration order