JavaScript Loop While

The while loop repeats code as long as a specified condition remains true. It's useful when you don't know how many iterations are needed beforehand.

Key Topics

Basic while

The while loop checks a condition before running each iteration, and stops when it's false.

let i = 0;
while (i < 3) {
    console.log(i);
    i++;
}

Output

> 0

> 1

> 2

Explanation: The loop runs while i < 3, starting at 0 and incrementing until 2.

Counter-Controlled Loops

You can use a variable as a counter in a while loop, incrementing it each iteration until it reaches a threshold.

JavaScript Usage in DOM

Use a while loop to continually check a condition (like user input validity) and break out once the condition is met, updating the DOM accordingly.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>While Loop in DOM</title>
</head>
<body>
    <h1>While Loop Demo</h1>
    <button onclick="loopNumbers()">Run Loop</button>
    <p id="result"></p>

    <script>
        function loopNumbers() {
            let num = 0;
            let output = "";
            while (num < 5) {
                output += num + " ";
                num++;
            }
            document.getElementById("result").textContent = output;
        }
    </script>
</body>
</html>

Key Takeaways

  • while: Runs as long as the condition is true.
  • Dynamic Iteration: Useful when the number of iterations isn't known upfront.
  • DOM Integration: Continuously check conditions and update the UI until they are met.