JavaScript > Loop

Do While loop in JavaScript

How to write Do While loop in JavaScript?


Do While loop

The Do while loop executes at least once and then repeats till the specified condition is true, this loop is a variant of the while loop. This loop executes the code once, before checking if the condition is true.

Alerting 5 times with the single code using Do While loop.

    <script>
        function TestFunction() {
            var i = 0;
            do {
                alert(i);
                i++;
            } while (i < 5);
        }
    </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 do while loop. That loop executes five times and gives alert messages from 0 to 4.

The above loop executes at least once and then check for the while condition, if the condition is true then it keeps executing else comes out of loop.

6 lines output by using Do 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;
        do {
            text += "<br> This is " + i;
            i++;
        }
        while (i < 6);
        document.getElementById("myId").innerHTML = text;
    }
</script>

6 lines output

We are returning 6 lines of output with the single declaration in JavaScript, by using Do While loop.

OUTPUT

 Views: 8659 | Post Order: 28



Write for us






Hosting Recommendations