JavaScript ยท Chapter 33 of 55

JavaScript While Loop

A `while` loop repeats a block of code as long as a condition remains true, checking the condition before each iteration. It is ideal when the number of repetitions isn't known in advance.

A `do...while` loop is similar but always executes the body at least once, since it checks the condition after running the block.

while loop

`while (condition) { ... }` checks the condition first; if false immediately, the body never runs.

do...while loop

`do { ... } while (condition);` guarantees the body runs at least once before checking the condition.

Example 1 (javascript)
let i = 0;
while (i < 3) {
  console.log(i);
  i++;
}
Output
0
1
2

The loop checks i < 3 before every iteration.

Example 2 (javascript)
let i = 5;
do {
  console.log(i);
  i++;
} while (i < 3);
Output
5

do...while runs once even though the condition is false immediately.

Key points

  • while checks its condition before running the loop body.
  • do...while always runs at least once.
  • Both loops need a way to eventually make the condition false.
  • Use while when the number of iterations is unknown ahead of time.
๐Ÿ’ก Note: Forgetting to update the loop's controlling variable is the most common cause of infinite while loops.

๐Ÿ“ Quick Quiz

1. When does while check its condition?

2. How many times does do...while run at minimum?

3. Which loop is best when iteration count is unknown?