Do..while Loops

Unlike the regular while loop, a do..while loop will run the block of code in the loop first and then check if the condition evaluates to true before it runs again (rather than testing the condition before running code in the loop). A do..while loop will always run at least once, even if the condition evaluates to false. This is an example of what is called a post-test repetition structure. On the other hand, a regular while loop (that only runs a block of code after a condition evaluates to true) is an example of a pre-test repetition structure.

Watch the video below, then scroll down the page to see the sample code explained.

Have a look at the sample code below for the do..while loop.

Here is the HTML code:

        <title>Do..while loops</title>
        <script src="script.js"></script>


Here is the JavaScript code:

// Set the counter to 1
var counter = 1;

// This is an example of a do-while loop
// Keep counting up by 1 until the counter reaches 10

}while(counter <= 10);

// Change the counter on Line 1 to 20 and run the program again. What happens?
// The number '20' will display in the console because it runs the loop once before checking the condition.
// We can see the block of code in the loop runs at least
// once even if the test condition evaluates to false.


Next tutorial: For loops