TExcelTAD
Home › JavaScript › JS While Loop

JavaScript While Loop

A while loop repeats its body as long as a condition stays true. Use it when you don't know in advance how many iterations you'll need — "keep going until the user guesses right", "until there are no more pages", "until the value converges".

while

js
while (condition) {
  // runs again and again while condition is truthy
}

The condition is checked before each iteration, so if it's false from the start, the body never runs.

js · try it yourself
let fuel = 3;
while (fuel > 0) {
  console.log(`Driving… fuel left: ${fuel}`);
  fuel--;
}
console.log("Out of fuel!");
Driving… fuel left: 3
Driving… fuel left: 2
Driving… fuel left: 1
Out of fuel!

An unknown number of steps

How many years until savings double at 7% interest? We can't easily say up front, so a while loop is a natural fit:

js · try it yourself
let balance = 1000;
let years = 0;
while (balance < 2000) {
  balance *= 1.07;
  years++;
}
console.log(`${years} years, final balance ${balance.toFixed(2)}`);
11 years, final balance 2104.85

Another classic: the Collatz sequence — halve even numbers, triple-plus-one odd ones, until you reach 1:

js · try it yourself
let n = 6;
const steps = [n];
while (n !== 1) {
  n = n % 2 === 0 ? n / 2 : 3 * n + 1;
  steps.push(n);
}
console.log(steps.join(" → "));
6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1

do…while

A do…while loop checks its condition after the body, so the body always runs at least once. It suits "do something, then decide whether to repeat" situations, such as retry logic or menus:

js · try it yourself
let attempt = 0;
let success = false;
do {
  attempt++;
  success = attempt === 3;   // pretend the 3rd try works
  console.log(`Attempt ${attempt}: ${success ? "ok" : "failed"}`);
} while (!success && attempt < 5);

let x = 100;
do {
  console.log("runs once even though x > 10");
} while (x < 10);
Attempt 1: failed
Attempt 2: failed
Attempt 3: ok
runs once even though x > 10

while vs for

Any for loop can be written as a while loop and vice versa. Choose the one that reads better:

Use When
for (let i = 0; i < n; i++) counting a known number of times
for…of going through a collection
while (cond) repeating until something changes; count unknown
do…while (cond) the body must run at least once
js · try it yourself
// the same loop, both ways
for (let i = 0; i < 3; i++) console.log("for", i);

let j = 0;
while (j < 3) {
  console.log("while", j);
  j++;
}
for 0
for 1
for 2
while 0
while 1
while 2

Avoiding infinite loops

If the condition never becomes false, the loop runs forever and freezes the page (or the playground). Make sure something in the body moves toward ending the loop:

js
let i = 0;
while (i < 10) {
  console.log(i);
  // forgot i++  →  infinite loop!
}

Tip: For loops that must end, add a safety limit: while (!done && tries < 100). If a playground ever hangs, reload the page.

Test yourself

How many times does the body of while (false) { … } run?

  1. 0
  2. 1
  3. Forever
  4. It is a syntax error

What is special about do…while?

  1. It runs at most once
  2. Its body always runs at least once
  3. It can't use break
  4. It checks the condition twice

What does let k = 0; while (k < 5) k += 2; console.log(k); print?

  1. 4
  2. 5
  3. 6
  4. 2