LESSON 14

While Loops

Learning objective: Repeat code while a condition stays true.

Understand

A while loop runs as long as its condition is true.

Use while when you do not know in advance how many times to repeat. Make sure something inside the loop moves the condition toward false, or you get an infinite loop.

Analogy: A while loop is like scooping water until the bucket is empty — you stop when the condition changes.

See It in Action

Counting down:

let n = 3;
while (n > 0) {
  console.log(n);
  n--;
}
How it works: The loop prints n and decreases it each pass, stopping when n reaches 0.

Try It Yourself

  1. Write a while loop that counts down from 5.
  2. Ensure it decreases each pass.
  3. Confirm it stops at 0.

Quick Quiz

When is a while loop a good choice?

Challenge

Use a while loop to count down from a number to zero.

Success condition: Your loop counts down and halts at zero.