Last updated

JavaScript While Loops

Definition: A while loop repeats as long as a condition is true. Use it when you do not know in advance how many repeats you need.

Example 1 — counting up

let i = 1;
while (i <= 5) {
  console.log(i);
  i++;
}

Each pass checks i <= 5. When i reaches 6 it stops.

Example 2 — avoiding infinite loops

Something inside must move toward stopping (here i++). Forget it and the loop never ends and freezes the page.

Example 3 — break and continue

  • break — exit immediately
  • continue — skip to the next pass
let i = 0;
while (i < 10) {
  i++;
  if (i === 3) continue; // skip 3
  if (i === 6) break;    // stop at 6
  console.log(i);
}

Example 4 — do...while

A do...while always runs at least once before checking:

let n = 0;
do {
  console.log("runs once even though n is 0");
} while (n > 0);

💡 for vs while: use for when you know the count; while when you are waiting for a condition.

Try it Yourself
Output

          
Ad · responsive