JavaScript

This page explains while and do...while loops, focusing on when their conditions are checked.

Goal: choose the right loop, update its state, and avoid accidental infinite loops.

while

Loops repeat a block while a condition remains true. A while loop checks the condition before each iteration, so it may run zero times.

JavaScript

let count = 1;
let total = 0;

while (count <= 100) {
  total += count;
  count += 1; // make progress toward the condition becoming false
}

console.log(total); // 5050

do...while

A do...while loop runs its block first and checks the condition afterward. It always runs at least once, even when the condition is initially false.

JavaScript

let answer;

do {
  answer = "default";
  console.log(answer);
} while (false); // the block has already run once

How to choose

Related topics