Javascript Tutorial -- Using For Loops
In Lesson 7, we introduced the "while" loop. The while loop is a good general purpose loop. Although we used it to build a counter in the example in that lesson, the while loop is flexible enough to use any time you want to repeat some action until some type of condition is met. For example, suppose you wanted to obtain user input from a form, check the user input for invalid data, and repeat if the user had entered any bad data. This is the type of processing that a while loop excells at. However, since we won't discuss user input until Lesson 17, I kept the example simple by creating a simple counter.
But in truth, there is a loop that is better for counting from some fixed starting point to some fixed ending point, and that is the "for loop" which is the topic of this lesson.
In the example in the previous lesson, we wanted to create a counter that would iterate from 99 to 0, and would substitute the value of the counter in the lyrics of the "99 Bottles" song. Since we know that we want to start at 99 and end at 0, a while loop -- as simple as it is -- is more complex than necessary. A for loop handles the start condition, the iteration and the test for the end condition for you, saving you from potentially creating a case where the counter does not get incremented, and thus creating an endless loop. Here's how you create a for loop:
<script type="text/javascript">
<!--
var Counter
for(Counter = 99; Counter >= 0; Counter--)
{
document.write(Counter + "bottles of...ahem...rootbeer on the wall")
}
//-->
</script>
Here is the general form of a for loop:
for(start condition; test; stepping function)
{
processing to be done
}
Did you catch the full implication of the general form above? While a simple counting operation is the most common usage of a for loop, it is not the only way a for loop can be used. Consider this snippet of code:
<script type="text/javascript">
<!--
var i
var List = new Array()
List[0] = "Tom"
List[1] = "Dick"
List[2] = "Harry"
List[3] = "Barb"
for(i = 0; List[i] != "Barb" ; i++)
{
document.write(List[i] + "<br>")
}
//-->
</script>
Although this example uses Arrays, which we haven't discussed yet, I think you can probably get the gist of the point I'm trying to make. The test can be any kind of true/false test you can devise, so long as there is a fixed starting point, a stepping function and a test that will eventually return a value of false.
Here is the "99 Bottles" example, implemented with a for loop rather than a while loop. Oh, I also modified it to count upwards from 0.