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...of gives values directly, not indexes — use array.entries() or a classic for loop if the index is also needed.
  • for...of works on any iterable (arrays, strings, Map, Set), not just arrays — it does not work directly on plain objects, which are not iterable (use Object.keys()/Object.entries() with for...of instead).
  • A while (true) { … break; … } loop is a legitimate pattern for “repeat until some condition met inside the loop body,” as long as a break is 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 for loop’s condition (<= vs <) — for...of avoids this class of bug entirely when only the values are needed.
  • An infinite loop from a while condition that’s never updated inside the loop body.
  • Trying for...of directly on a plain object — it throws a TypeError because plain objects aren’t iterable.

Runtime notes

All three loop forms are core ECMAScript with identical behavior in every browser and Node version.

Taught in these lessons

Related reference