for, while, and for...of
Three loop forms — for when counting or indexing, while when the iteration count isn't known up front, for...of when iterating a collection's values.
for (init; cond; update) { } / while (cond) { } / for (const x of iterable) { }
Purpose
for repeats a block a counted number of times using an index. while repeats as long as a
condition holds, without a built-in counter. for...of iterates the values of an array, string, or
other iterable directly, without manual indexing.
Syntax
for (let i = 0; i < 5; i++) {
console.log(i);
}
let attempts = 0;
while (attempts < maxAttempts && !success) {
attempts++;
success = tryConnect();
}
for (const item of ['apple', 'banana', 'cherry']) {
console.log(item);
}
Behavior notes
for...ofgives values directly, not indexes — usearray.entries()or a classicforloop if the index is also needed.for...ofworks on any iterable (arrays, strings,Map,Set), not just arrays — it does not work directly on plain objects, which are not iterable (useObject.keys()/Object.entries()withfor...ofinstead).- A
while (true) { … break; … }loop is a legitimate pattern for “repeat until some condition met inside the loop body,” as long as abreakis reachable. do...while(not shown above) runs its body once before checking the condition — rarely needed as a beginner, but exists for “always run at least once” cases.
Common mistakes
- Off-by-one errors in a classic
forloop’s condition (<=vs<) —for...ofavoids this class of bug entirely when only the values are needed. - An infinite loop from a
whilecondition that’s never updated inside the loop body. - Trying
for...ofdirectly on a plain object — it throws aTypeErrorbecause plain objects aren’t iterable.
Runtime notes
All three loop forms are core ECMAScript with identical behavior in every browser and Node version.