CodeBlanks Logo Icon CodeBlanks

The while loop

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.

Practice 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.

Starter code

script.js
// Count down from 5 to 1
let count = 5;

Sample solution

script.js
let count = 5;
while (count > 0) {
  console.log(count);
  count--;
}

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is the condition checked in a while loop?

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

Explanation: 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

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

Explanation: count-- decreases the counter each step, so the condition eventually becomes false.

3 What does this code print?

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

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

All lessons in Beginner