Loops
Loops repeat a body until a condition fails. JavaScript has for, while, do...while, for...of over iterables, and for...in over object keys.
Detailed Explanation
A loop is a way to do the same work for many values. The four families are not interchangeable.
while (cond) { ... } tests first, then runs. If cond is already falsy, the body never runs. do { ... } while (cond) runs the body once before testing, so it always executes at least once. Use do...while only when that first pass is required, such as reading input until it is valid.
The C-style for (init; test; step) is the general counter loop. init runs once. test runs before every iteration. step runs after each body. Any of the three slots can be empty: for (;;) is an infinite loop. let i = 0 inside init is scoped to the loop; var i = 0 leaks to the enclosing function.
for...of walks an iterable: arrays, strings, Map, Set, typed arrays, and anything with [Symbol.iterator]. Each iteration binds the value. This is the default loop for collections in modern code.
for...in walks enumerable property keys of an object, including inherited ones. It is for objects, not arrays. On an array it yields index strings, skips holes, and can pick up extra enumerable properties. Prefer for...of, array.forEach, or Object.keys when the data is a list.
break leaves the innermost loop. continue skips to the next iteration. A label (outer: for (...)) lets break outer leave a nest, which is legal and rarely clearer than extracting a function.
for await...of walks an async iterable, awaiting each item. It belongs in async functions. Use it for streams and paginated async sources, not for ordinary arrays.
What it costs you: blocking the thread. A tight for over a million items is fine. A tight for that also does DOM work, or a while (true) without an await or break, freezes the page. for...in on arrays is both slower and wrong. array.forEach cannot break; if you need early exit, use for...of or .some.
Reach for for...of for values, for when you need the index and a custom step, while when the stop condition is not a counter, and never for...in for arrays.
Code Examples
const names = ["Ada", "Bram", "Cleo"];
// Values, in order. This is the usual choice for arrays.
for (const name of names) {
console.log(name);
}
// Index plus value when you need both.
for (const [i, name] of names.entries()) {
console.log(i, name);
}
// C-style when the step is not +1.
const evens = [];
for (let i = 0; i < 8; i += 2) {
evens.push(i);
}
console.log(evens); // => [ 0, 2, 4, 6 ]const user = { id: 7, email: "ada@example.com" };
const keys = [];
for (const key in user) {
keys.push(key);
}
console.log(keys); // => [ 'id', 'email' ]
// for...in on arrays yields index strings and is the wrong tool.
const xs = ["a", "b"];
xs.extra = "nope";
const seen = [];
for (const k in xs) {
seen.push(k);
}
console.log(seen); // => [ '0', '1', 'extra' ]let n = 3;
while (n > 0) {
n -= 1;
}
console.log(n); // => 0
let tries = 0;
do {
tries += 1;
} while (tries < 1);
console.log(tries); // => 1Common Gotchas
`for...in` is not for arrays
it walks keys, including inherited enumerable properties, and skips holes. Use `for...of` or a numeric `for`.
`forEach` cannot break
`return` inside `forEach` is only `continue`. Use `for...of` when you need to stop early.
Closures over `var` in a loop share one binding
all callbacks see the final value. `let` creates a fresh binding per iteration.
`for await...of` needs an async iterable
using it on a plain array works (it awaits each already-resolved value) but adds pointless microtasks. Use `for...of` for sync data.