Loops repeat an action several times without rewriting the same code. They remove repetition and save a great deal of time.

The for loop

Ideal when you know how many repetitions you need:

for (let i = 0; i < 5; i++) {
  console.log("Tour numéro " + i);
}

It has three parts: an initialisation (let i = 0), a condition to keep going (i < 5) and an increment (i++).

The while loop

It repeats for as long as a condition stays true:

  • Handy when you do not know in advance how many rounds will be needed.
  • Careful: make sure the condition eventually becomes false, otherwise the loop runs forever and freezes the page.

Key takeaway: for when you know the number of rounds, while when you repeat as long as a condition holds. Always plan a way out!