Iterating over collections is one of the most common things code does.
The classic for loop has an initialiser, a condition and an update:
for (let i = 0; i < 5; i++) console.log(i);while (cond) { ... } repeats as long as the condition is truthy; do { ... } while (cond) always runs at least once.
For walking through collections, prefer `for...of`. It iterates over the values of any iterable — arrays, strings, Maps, Sets, NodeLists:
for (const fruit of ["apple", "pear"]) console.log(fruit);When you also need the index, use for (const [i, fruit] of fruits.entries()).
`for...in` is different: it iterates over the enumerable property names (keys, always strings) of an object, including inherited ones. Use it rarely, and never for arrays; for objects, Object.keys(obj) or Object.entries(obj) with for...of is clearer.
Two keywords control a loop from inside:
breakexits the loop immediately.continueskips to the next iteration.
Labels (outer: for (...) then break outer) let you break out of nested loops, but extracting a function and returning is usually clearer.
Declaring the loop variable with let or const gives each iteration its own binding — this matters when callbacks created in the loop run later. With var, they would all share one variable.
Arrays also have methods like forEach, map and filter that replace many loops; you'll meet them in the array-methods lesson.
Example
const scores = { ada: 90, alan: 72, grace: 85 };
for (const [name, score] of Object.entries(scores)) {
if (score < 80) continue; // skip low scores
console.log(`${name}: ${score}`); // ada: 90, grace: 85
}
let n = 0;
while (true) {
n++;
if (n * n > 50) break; // stop at the first square > 50
}
console.log(n); // 8
for (const ch of "hey") console.log(ch); // h, e, y
for (const key in ["x", "y"]) console.log(typeof key); // "string" twiceRemember
for...ofiterates values of arrays, strings, Maps and other iterablesfor...initerates property names (strings) — avoid it for arraysbreakexits,continueskips to the next iteration
Watch out for
- Using
for...inon an array and getting string indexes (and inherited keys) instead of the elements.