Lesson 20 +10 XP

While and Do While

While and Do While

while and do...while loops repeat code while a condition is true.

The while loop

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

The condition is checked before each run. If it is false at the start, the code never runs.

The do...while loop

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);

The code runs once first, then the condition is checked. So a do...while always runs at least one time.

while vs do...while

  • while: condition first, may run zero times.
  • do...while: runs first, then checks, always runs at least once.

Infinite loop warning

If the condition never becomes false, you get an infinite loop that freezes your page:

while (true) {
  // make sure something changes or stops this!
}

Always make sure something in the loop changes the condition.

TL;DR

  • while checks before running.
  • do...while runs once before checking.
  • Be careful not to create infinite loops.