Javascript: More Loops and Events
(Page 1 of 4 )
In our last tutorial we covered functions and a portion of loops, leaving off at the While loop. In this tutorial we will continue with the Do While Loop and hopefully work our way through to a taste of JavaScript Events.
Do While
The Do While is a variation on our pal the While loop. It is used when you want to execute a block of code at least once. After it does the initial run through, it will then continue to loop while your criteria is met. Once the criteria is no longer met, it will exit the loop and move on.
<html>
<body>
<script type="text/javascript">
i = 0
do
{
document.write("I've had this many beers: " + i)
document.write("<br />")
i++
}
while (i <= 4)
</script>
</body>
</html>
This will print out:
I've had this many beers: 0
I've had this many beers: 1
I've had this many beers: 2
I've had this many beers: 3
I've had this many beers: 4
The way the program works is that it assigns a value to the counter variable (0 in this instance), then goes through the loop once, writing out how many beers I have had. No matter what criteria is met or not met, it will always at least print:
I've had this many beers: 0
We then have it print a break to separate the data on separate lines. Finally, it increments the value of our variable by one and checks the criteria at the end (as opposed to at the beginning, which is how we force it to run through at least once). If the criteria is met, it loops again. If not, it breaks out of the loop.
Next: Break Dancing >>
More JavaScript Articles
More By James Payne