The while Loop

Grade 5, page 2 of 11. A one-minute read.

The simplest loop is the while loop. It keeps repeating a block of code while a condition is true:

JavaScript
let countdown = 5;

while (countdown > 0) {
  console.log(countdown);
  countdown--;
}

console.log("🚀 LIFTOFF!");

It prints

5
4
3
2
1
🚀 LIFTOFF!

It looks a lot like an if statement, doesn't it? The difference is that an if runs its block once, but a while keeps going back to the top and checking the condition again, over and over, until it becomes false.

Let's trace through it:

Roundcountdowncountdown > 0?What happens
15trueprint 5, countdown becomes 4
24trueprint 4, countdown becomes 3
33trueprint 3, countdown becomes 2
42trueprint 2, countdown becomes 1
51trueprint 1, countdown becomes 0
60falsestop looping!

Each trip through the loop is called an iteration. Our countdown loop iterated five times.

Every good loop has three ingredients:

  1. A starting point: let countdown = 5;
  2. A condition that decides whether to keep going: countdown > 0
  3. An update that moves things toward the end: countdown--

Forget any one of them, and things go wrong. Especially the third one...

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning