A do while loop is a special kind of loop. It’s a variation of the while loop, but with a special addition. Let’s learn how to use a do while loop.
Creating A Do While Loop
Clear your script and update your code to this.
var i = 0;
var total = 0;
total += 10;
}while ( i < 10 );
alert( total );
You’ll notice everything is the same in our last tutorial, except our loop is a tad different. A do while loop is structured with the keyword do at the beginning of the loop and the keyword while at the end.This is because a do while loop runs at least once before it checks the condition.
This is useful when you’re certain you want to execute the block of code at least once before running it again. You also have to add a semi-colon at the end of your while statement. If you run this code, then you should get an alert message saying 100.
We’ve been talking about the basics for a bit and you may not fully understand the full capabilities of each loop yet. We still have some fundamentals to cover, but soon we’ll be practicing how to use these loops in real world situations and examples.