← All lessons/Loops· Lesson 16 of 32

The while loop

Repeat code as long as a condition stays true with the while loop.

About 7 min

Loop while something is true

A while loop is a for loop's plainer cousin. It keeps running its body as long as a condition is true. You manage the counter yourself: declare it before the loop, check it in the condition, and change it inside.

let i = 0;
while (i < 5) {
  // this runs 5 times
  i++;
}
A while loop counting to 5.

This does the exact same thing as for (let i = 0; i < 5; i++) — the for loop just bundles the three parts onto one line. Here's a row of circles built with a while loop:

A while loop drawing a row of 7 circles.

Don't forget to change the counter!

If you leave out the i++, the condition i < 7 stays true forever and the loop never stops. Always make sure something inside the loop moves you toward the condition becoming false.

Your turn

Rebuild a row of circles with a while loop. Set let i = 0 before the loop, run while (i < 5), draw ellipse(i * 60 + 40, 200, 40, 40) inside, and don't forget i++.

Hints