iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

JS Loop While

while and do…while loop while a condition is true. Use them when you don't know how many iterations you need upfront.

The two forms

JS
// Check first, then run
while (queue.length > 0) {
  process(queue.shift());
}

// Run first, then check — always runs at least once
let input;
do {
  input = prompt("Enter a value:");
} while (!input);

while vs. for

LoopBest for
forKnown iteration count, index needed.
for…ofIterating items in a collection.
while"Keep going until some condition is met" — game loops, polling, draining a queue.
do…whileNeed to run the body at least once before checking.

Avoiding infinite loops

JS
// ❌ The condition never changes
let i = 0;
while (i < 10) {
  console.log(i);
  // forgot to increment i!
}

// ✓ Always update the variable that controls the loop
let i = 0;
while (i < 10) {
  console.log(i);
  i++;
}
Tip: If you find yourself fighting the loop condition, restructure the data. arr.filter / map / reduce turn most "while" patterns into a clean pipeline.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from JS Loop While!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Drain a queue until it is empty.

(queue.length > 0) { process(queue.shift()); }

Test yourself

Q1. Which loop ALWAYS runs at least once?
Q2. A `while` loop without an exit condition…
Q3. Prefer `while` over `for` when…

Discussion

Loading…