Do..while Loops

Unlike the regular while loop, a do..while loop will run once first and then check the condition before it runs again. The loop will always run at least once, even if the condition evaluates to false. This is an example of a post-test loop structure. On the other hand, a regular while loop that only runs while a condition evaluates to true is an example of a pre-test loop 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 (post-test loop structure).

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Do While Loops</title>
 <script type="text/javascript">
 
 // Unlike the regular WHILE loop, a DO WHILE loop will run once first and then check the condition
 // before it runs again. The loop will always run at least once, even if the condition evaluates to false.
 // This is an example of a post-test loop structure.
 
 var counter=1;
 
 do{
 document.write("This is line "+counter+"<br/>");
 counter++; //increase counter value by 1
 }while(counter<=10);
 
 // Change the counter to 11 and run the program again. What happens?
 // One line will still print because it runs the loop once before checking the condition.
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: For loops