CodeBlanks Logo Icon CodeBlanks

The while loop

JavaScript course · Beginner · Lesson 37/133

Learn the while loop that runs as long as the condition is true.

The while loop

The while loop repeats a block as long as the condition is true. The condition is tested first; if false, the body never runs. That's why while is also called a pre-condition loop.

let count = 3;
while (count > 0) {
  console.log(count);
  count--;
}

Here count decreases each step. When count > 0 becomes false, the loop stops. If you forget count--, the condition stays true forever and the loop never ends; that's an infinite loop.

The infinite loop trap

If the condition never becomes false, the while loop runs forever. This is called an infinite loop and it can freeze the browser.

let n = 1;
while (n > 0) {
  console.log(n);
  // n is never changed
}

Here n stays 1; the condition n > 0 is always true. The loop never ends. To prevent this, the body must change the counter: decrement, increment, or exit with break. Otherwise the program locks up and can only be stopped by closing the browser.

Exercise Count down from 5 to 1

Use a while loop to count down from 5 to 1 and print each number with console.log. Decrement the counter each step.

Show example solution
let count = 5;
while (count > 0) {
  console.log(count);
  count--;
}

Test yourself

  1. When is the condition checked in a while loop?

    • After the loop
    • Only once at the start
    • Before each step
    • Only on errors
    Show answer

    Before each step — while tests the condition before each step. If the first test is false, the body never runs.

  2. Decrement the counter to avoid an infinite loop

    let count = 3;
    while (count > 0) {
      console.log(count);
      ____;
    }
    Show answer
    let count = 3;
    while (count > 0) {
      console.log(count);
      count--;
    }
  3. What does this code print?

    let count = 3;
    while (count > 0) {
      console.log(count);
      count--;
    }
    • 3, 2, 1
    • 1, 2, 3
    • 3, 2, 1, 0
    • 0, 1, 2, 3
    Show answer

    3, 2, 1 — count starts at 3, is printed while greater than 0, and decreases. So 3, 2, 1 are printed.

All lessons in Beginner