JavaScript while

Loop Until a Condition Is False

JavaScript while

`while` runs while a condition is true. Reach for it when you don't know how many iterations you'll need.

3 min read Level 1/5 #while#do-while#loops
What you'll learn
  • Write a `while` loop
  • Choose between `while` and `do..while`
  • Avoid infinite loops

while keeps running its body for as long as the condition is true. Unlike for, there’s no counter built into the syntax — you manage the state yourself.

while script.js
let i = 0;

while (i < 3) {
  console.log(i);
  i++;
}
// 0, 1, 2
▶ Preview: console

This is equivalent to for (let i = 0; i < 3; i++) { … }. Use while when “until something happens” reads better than counting.

Loop until condition script.js
let dice;
let rolls = 0;

while (dice !== 6) {
  dice = Math.floor(Math.random() * 6) + 1;
  rolls++;
}

console.log(`Got a 6 after ${rolls} rolls`);
▶ Preview: console

do..while — Run At Least Once

do..while checks the condition AFTER the body. The body runs at least once.

do..while script.js
let n = 10;

do {
  console.log(n);
  n--;
} while (n > 0);
// 10, 9, 8, ..., 1
▶ Preview: console

do..while is rare — useful when “we want to ask the user at least once” patterns. For most loops, plain while is fine.

Avoiding Infinite Loops

A while loop forgets the condition is your responsibility. If nothing inside the body ever makes the condition false, you have an infinite loop.

let n = 0;
while (n < 10) {
  console.log(n);
  // Forgot n++ — n stays at 0 forever
}

If your tab freezes, this pattern is the usual culprit. Modern browsers will eventually offer to kill the page, but you’ll lose unsaved state.

When to Use Each Loop

LoopReach for it when…
forIterating a fixed count or numeric range
for..ofIterating values in an array, string, set, map
for..inIterating an object’s keys
whileLooping until a condition becomes false
do..whileSame, but the body must run at least once
forEachSide-effect-y iteration, no break needed
map/filter/reduceBuilding a new array or value from existing items

Up Next

Two keywords that change the flow inside any loop — break and continue.

JavaScript break & continue →