JSJavaScript
BeginnerLesson 4 of 16

Loops – JavaScript

for, for...of, for...in, while, break and continue.

The classic for loop has three parts: start, condition, step. For collections you usually use for...of.

for (let i = 0; i < 3; i++) {
  console.log("Round", i);
}

for (const frucht of ["Apple", "Pear", "Cherry"]) {
  console.log(frucht.toUpperCase());
}

for (const [i, f] of ["A", "B"].entries()) {
  console.log(i + 1, f);
}

for...of iterates over the values (arrays, strings, sets, maps …). for...in iterates over the keys of an object. You usually iterate over object entries with Object.entries:

const person = { name: "Ada", alter: 36 };
for (const key in person) {
  console.log(key, person[key]);
}
for (const [k, v] of Object.entries(person)) {
  console.log(k + " = " + v);
}
for (const zeichen of "Hi!") {
  console.log(zeichen);
}

while runs as long as a condition holds. break ends the loop, continue jumps to the next iteration. do...while checks only after the first pass.

let n = 0;
while (true) {
  n++;
  if (n % 2 === 0) continue;
  if (n > 7) break;
  console.log(n);   // 1 3 5 7
}
Warningfor...in over an array yields the indices as strings (and possibly inherited properties). For arrays, use for...of or array methods like forEach.
TipWith array.forEach(fn) there is also a functional loop – but break and continue do not work there. If you need to stop early, use for...of, some or find.