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
| Loop | Best for |
|---|---|
for | Known iteration count, index needed. |
for…of | Iterating items in a collection. |
while | "Keep going until some condition is met" — game loops, polling, draining a queue. |
do…while | Need 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()); }
The keyword same as the topic name.
Discussion
Loading…