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.
<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.
<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>
We are returning 6 lines of output with the single declaration in JavaScript, by using Do While loop.
OUTPUT
Views: 8659 | Post Order: 28