Repeating While a Condition Is True

A loop runs a block of code again and again. The simplest loop is while. It checks its condition before every pass, and it keeps going as long as the condition is true:

let i = 1;
while (i <= 3) {
  console.log("lap", i);
  i++;
}

Output:

lap 1
lap 2
lap 3

Follow it step by step, the way JavaScript does. Is 1 <= 3? Yes, so the block runs and i becomes 2. Is 2 <= 3? Yes, so it runs again and i becomes 3. Is 3 <= 3? Yes, one more time, and i becomes 4. Is 4 <= 3? No. The loop ends, and the program continues after it.

A while loop that should stop needs three parts:

  1. A variable that the condition watches (i).
  2. The condition itself (i <= 3).
  3. A step inside the block that moves toward the end (i++).

Notice that i is declared with let, not const, because the loop changes it.

If you forget the step, the condition never changes, and the loop never ends. This is called an infinite loop. On your own computer, it keeps running until you stop the program. Here, the runtime stops it for you. If the loop prints nothing, you see Time limit exceeded after about 5 seconds. If the loop prints on every pass, it usually crashes sooner with a long, confusing error from Node. If you see either of these in an exercise, check your loops first.

There is also a do...while loop. It runs the block once before it checks the condition, so the block always runs at least one time:

let tries = 5;
do {
  console.log("try", tries);
  tries++;
} while (tries <= 3);

Output:

try 5

The condition 5 <= 3 is false, but the block already ran once. You will not need do...while often. A plain while is the normal choice.

When you know how many passes you need, the for loop in the next lesson is shorter. Use while when you repeat until something happens, for example until the user guesses right.

In the exercise, write a countdown from n to 1 with a while loop, then print Liftoff!.