CPCODELAB
JavaScript

Loops: for, while, for..of, for..in

10 min read

Loops

Loops repeat a block of code. JavaScript has several loop forms; choose the one that best expresses your intent.

Classic for Loop

javascript
for (let i = 0; i < 5; i++) {
  console.log(i); // 0 1 2 3 4
}

while and do...while

javascript
let n = 1;
while (n < 10) {
  n *= 2;
}
console.log(n); // 16

// do...while executes at least once
do {
  n -= 1;
} while (n > 10); // exits immediately after first iteration

for...of (Iterables)

for...of iterates over any iterable — arrays, strings, Sets, Maps, NodeLists, etc. It gives you the values, not the indices.

javascript
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}

// With index via entries()
for (const [i, fruit] of fruits.entries()) {
  console.log(i, fruit);
}

for...in (Object Keys)

for...in iterates over an object's enumerable property keys (including inherited ones). Avoid using it on arrays — the indices come as strings and inherited properties can leak in.

javascript
const person = { name: "Alice", age: 30, city: "NYC" };
for (const key in person) {
  if (Object.hasOwn(person, key)) {
    console.log(key, person[key]);
  }
}

break and continue

javascript
for (let i = 0; i < 10; i++) {
  if (i === 3) continue; // skip 3
  if (i === 7) break;    // stop at 7
  console.log(i);        // 0 1 2 4 5 6
}
Ready to test yourself?
Practice JavaScript— quiz & coding exercises