Menu

JavaScript While Loops: while, do...while, break and continue

How while and do...while loops work in JavaScript — when to reach for them instead of for, and how to avoid infinite loops.

When You Don't Know How Many Iterations You Need

A for loop shines when you know the range upfront — "do this 10 times," "walk every index of this array." A while loop is for the other case: keep going until something changes. You don't know how many iterations it'll take, only the condition that makes you stop.

The shape is minimal:

index.js
Output
Click Run to see the output here.

JavaScript evaluates the condition in parentheses. If it's truthy, the block runs. Then it checks the condition again, and again, until it becomes falsy. Miss the count++ and the condition never changes — welcome to an infinite loop.

The Mental Model: Check, Run, Repeat

Three things have to be true for a while loop to make sense:

  1. Something the condition depends on.
  2. A way for the body to change that something.
  3. Eventually, the condition becomes false.

Leave out any one and you're in trouble. The classic bug is forgetting step 2:

let count = 0;

while (count < 5) {
    console.log(count);
    // forgot to increment count — loops forever
}

That runs until you kill the process. Real damage when it happens on a server. Always ask yourself: what in the body is going to make the condition false?

A Real Use Case: Unknown Stopping Point

Here's where while beats for. You're consuming items from somewhere and you don't know how many there are until you've drained them:

index.js
Output
Click Run to see the output here.

shift() removes and returns the first item. The loop runs as long as the queue has something in it, and exits naturally when it's empty. You could write this with a for loop, but you'd be fighting the shape of the problem — while reads like the intent.

do...while: Run First, Ask Questions Later

do...while flips the order: run the body, then check the condition. That guarantees at least one iteration:

index.js
Output
Click Run to see the output here.

The body always runs once, even if the condition is false right out of the gate. Compare that with plain while, where a false condition means zero iterations.

The everyday case: prompting a user, validating the answer, and re-prompting if it's bad. You always want to ask at least once, so do...while fits.

Note the semicolon after the closing ) — unlike while and for, do...while needs one.

break: Bail Out Early

break exits the nearest loop immediately. It's how you stop when the natural condition isn't quite right for the job:

index.js
Output
Click Run to see the output here.

Once break runs, nothing else in the loop executes — not the rest of the body, not another condition check. You're out.

while (true) with break

When the stopping condition is easier to express inside the body than in the header, flip the structure: loop forever and break out when you're done.

index.js
Output
Click Run to see the output here.

Two exits: success and a safety cap. The safety cap matters. while (true) with no guaranteed break path is an infinite loop waiting to happen.

continue: Skip to the Next Iteration

continue jumps to the next condition check, skipping the rest of the current iteration's body:

index.js
Output
Click Run to see the output here.

One gotcha: if the thing that moves your loop forward lives after the continue, you've just built an infinite loop. In the example above, n++ is before the continue, so we're safe. Put it after and n gets stuck on an even number forever.

while vs for: Which to Use

A mechanical rule of thumb:

  • Counting or indexing a known rangefor. for (let i = 0; i < arr.length; i++) keeps the counter setup, condition, and step all in one line.
  • Iterating a collectionfor...of. Cleaner than managing an index.
  • Looping until some state changeswhile. Processing a queue, polling, consuming a stream, retrying until success.
  • Always run at least oncedo...while.

They're interchangeable in theory — any for can be rewritten as a while and vice versa. But picking the one that matches the shape of the problem makes the code self-documenting.

Infinite Loops: The One Rule

Every while loop needs a clear answer to: what makes this stop?

Either the condition in the header will eventually become false, or there's a break that definitely runs. If you can't point at one of those, the loop isn't finished yet.

// Bad: condition never changes
let ready = false;
while (!ready) {
    console.log("waiting...");
    // nothing in here flips `ready`
}

// Good: the body affects the condition
let ready = false;
let checks = 0;
while (!ready) {
    checks++;
    if (checks >= 3) ready = true;
}

In a browser, an infinite loop freezes the tab. In Node, it pegs a CPU core until you kill the process. Worth catching before they ship.

Next: for...of and for...in

while handles the "until something changes" case. For walking through arrays, strings, and objects item by item, JavaScript has two more loop forms designed exactly for that — for...of and for...in, up next.

Frequently Asked Questions

What is a while loop in JavaScript?

A while loop runs its body repeatedly as long as a condition is truthy. JavaScript checks the condition first, runs the block, then checks again. If the condition is false the first time, the body never runs at all.

What's the difference between while and do...while?

while checks the condition before running the body, so zero iterations is possible. do...while runs the body once, then checks the condition — so it always runs at least once. Use do...while when the first iteration has to happen unconditionally, like prompting a user for input.

How do I break out of a while loop in JavaScript?

Use the break statement to exit the loop immediately, or continue to skip to the next iteration. break is how you implement while (true) loops safely — loop forever, then break when some condition inside the body is met.

Learn to code with Coddy

GET STARTED