Javascript: More Loops and Events - Break Dancing
(Page 2 of 4 )
If you were to see my enormous body today, you would never know that at one point in my life I was a break dancing master. My slick moves allowed me to defy the laws of gravity. Granted I was like eight years old and fat, but no one could do the worm like me. Word to your mother's uncle.
In fact, it was the Summer of Foot Loose, (well for me anyway; in retrospect the movie was playing on regular television by the time I saw it) and I made my mother tell me on an hourly basis that I did in fact 1) look like Kevin Bacon and 2) dance like Kevin Bacon.
Well, since we are talking about breaks (how's that for a segue), you will note that Javascript has to two types of special statements for you to use inside of loops. They are the Break and the Continue.
Breaking It Down
The Break command is used to exit a loop and continue on to the code after the loop. Let's say that I didn't really want you to know how many beers I drank. I could write a code that would exit out of the loop when the value of my counter got so high it was embarrassing:
<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){break}
document.write("I drank this many beers: " + i)
document.write("<br />")
}
</script>
</body>
</html>
This would print out:
I drank this many beers: 0
I drank this many beers: 1
I drank this many beers: 2
The code works by assigning a starting value to the counter variable, then saying that if the value is less than or equal to 10, keep doing the loop, and increment the value of the counter by 1 each time through the loop.
It then gives us a conditional statement, in this case an If statement, that says if the value of our counter is equal to 3, break out of the loop and don't print any more, and skip to the next block of code.
So even though we initially told the loop to run ten times, because our special criteria was met, it broke out of the loop after only three times.
Next: And So it Continues >>
More JavaScript Articles
More By James Payne