JavaScript > Loop

While loop in JavaScript

How to write While loop in JavaScript?


While Loop

The While Loop is used to execute a block of statements till specified condition is true, if the condition becomes false the While Loop terminates. This is the very basic loop in JavaScript.

Alerting 5 times continuously by using While loop.

   <script>
        function TestFunction() {
            var i = 0;
            while (i < 5) {
                alert(i);
                i++;
            }
        }
    </script>
    
    <input type="button" id="btnTest" onclick="TestFunction()" value="Click me" />

In above code snippet, on click of button TestFunction() shall fire that will run a while loop. That loop executes five times and gives alert messages from 0 to 4.

NOTE: Make sure that you are incrementing/decrementing (as the case may be) the value you are going to test, otherwise an indefinite loop begins that may stuck your browser.

6 lines output with single code by using while loop.

<p>Click the button to show the result.</p>
<input type="button" value="Button" onclick="myLoop()"/>
<p id="myId"></p>

<script>
    function myLoop() {
        var text = "";
        var i = 0;
        while (i < 6) {
            text += "<br>This is " + i;
            i++;
        }
        document.getElementById("myId").innerHTML = text;
    }
</script>

6 lines output

We are returning the 6 lines of output with a single code by using JavaScrip While loop.

OUTPUT

 Views: 5316 | Post Order: 27



Write for us






Hosting Recommendations