Javascript Tutorial -- While Loops



In Lesson 5 I discussed the concept of structured programming, and I mentioned that writing code in modular, reusable pieces was one of the tenets of writing structured code. Another tenet of structured programming is avoiding the use of "GOTO" statements. Using code of the form "if-then-goto-else-goto" is generally considered bad form, as it leads to code that jumps unpredictably from point to point -- often called "spaghetti code". Using functions is one way to avoid spaghetti code; another is to use loops to repeat a task until some threshold is met.

Javascript supports two types of loops: the "while loop", which we will discuss in this lesson, and the "for loop", which we will intorduce in the next lesson.

Suppose you want to write all 100 verses of the song "99 Bottles of...ahem...Rootbeer on the Wall". OK, that's an odd thing to script in a web page, but work with me here :) You could just type in all 100 verses, but that seems awfully tedious, and let's face it, you and I both have better things to do. Computers, however, excel at performing repetitive, tedious tasks that you and I are too lazy^H^H^H^Hintelligent to do ourselves. Wouldn't it be great if there were a way to count from 99 down to 0, and just substitute the number of bottles in the verse with a variable that was decremented at each count? It seems like something we should be able to do easily enough in Javascript -- after all, we know how to use variables, and we've learned how to use the decrement operator. Now all we have to learn is how to keep repeating the task as we count from 99 to 0, and this is what a loop will let us do:
        <script type="text/javascript">
          <!--
            var Counter = 99

            while (Counter >= 0)
              {
                document.write(Counter + "bottles of...ahem...rootbeer on the wall.
") Counter-- } //--> </script>
Essentially, a while loop will keep running the code found between the two curly braces until the condition between the parenthesis is no longer true. The important thing to remember here is that if the code between the curly braces doesn't ever change the condition between the parenthesis, the script will never proceed beyond the while loop. A loop that never terminates is called an "endless loop" and is generally considered to be a BAD THING (TM).

Here is the "99 Bottles" script, minus a verse or two...or 89.