How to repeat with loops

Count with for

A for loop groups initialization, condition, and update. It is useful when the number of iterations is known.

for (let count = 1; count <= 3; count += 1) {
  console.log(`Count: ${count}`);
}

Use for...of with arrays

for...of reads each value in an iterable and avoids manual indexes.

const colors = ["red", "green", "blue"];
for (const color of colors) {
  console.log(color.toUpperCase());
}

Repeat while a condition holds

A while loop suits an unknown number of repetitions. Ensure something can eventually make its condition false.

let remaining = 3;
while (remaining > 0) {
  console.log(remaining);
  remaining -= 1;
}
console.log("Go!");

Control and protect loops

  • break exits the nearest loop
  • continue skips to its next iteration
  • Check loop boundaries to prevent off-by-one errors
  • Avoid blocking infinite loops, especially in a browser tab