JavaScript While Loop
A while loop repeats code as long as a condition stays true, which suits situations where you do not know the number of iterations in advance.
Looping until a condition changes
Where a for loop shines when you know how many times to repeat, a while loop is the natural choice when you simply want to keep going until something becomes false. It checks the condition first, and if it is true the body runs; then it checks again, repeating until the condition fails.
A basic while loop
<!DOCTYPE html>
<html>
<body>
<h2>A basic while loop</h2>
<script>
let count = 0;
while (count < 3) {
console.log("count is", count);
count++;
}
// count is 0
// count is 1
// count is 2
</script>
</body>
</html>The do...while variant
A do...while loop is a close relative that checks its condition at the end instead of the beginning. This guarantees the body runs at least once, which is handy when you need to perform an action before you can even test whether to continue, such as reading input and then validating it.
do...while runs at least once
<!DOCTYPE html>
<html>
<body>
<h2>do...while runs at least once</h2>
<script>
let n = 10;
do {
console.log("value:", n);
n++;
} while (n < 5);
// value: 10
// The body ran once even though 10 < 5 is false
</script>
</body>
</html>- while checks the condition before the first pass, so it may run zero times.
- do...while checks the condition after each pass, so it always runs at least once.
- Both loops depend on the body eventually making the condition false.
- Use them when the number of repetitions is not known ahead of time.
A practical example
Because while loops keep running until a goal is met, they fit tasks like consuming a queue, retrying until success, or processing data of unknown size. In the example below the loop halves a number until it drops below one, something you cannot easily express as a fixed count.
Repeating until a target is reached
<!DOCTYPE html>
<html>
<body>
<h2>Repeating until a target is reached</h2>
<script>
let value = 40;
let steps = 0;
while (value >= 1) {
value = value / 2;
steps++;
}
console.log(steps, "halvings needed"); // 6 halvings needed
</script>
</body>
</html>