JavaScript Primers #25

By Joe Burns

http://www.htmlgoodies.com/primers/jsp/article.php/3478381/JavaScript-Primers-25.htm (Back to article)

Use these to jump around or read it all


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment


The Concept

This example looks at the While loop. Remember that usually you use For loops when you know how many times you want to perform a loop and While loops when you are not sure how many times you want to perform a loop. This sample will break the rule! We're doing this to show you how to use variables to count iterations in a loop and to help you get ready for your assignment.


The Script

<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
  loops=3
  num=1
  while (num <= loops)
     {
     document.write("Happy ")
     num=num+1
     }
     document.write("Birthday")
</SCRIPT>
</BODY>
</HTML>

The Script's Effect


Deconstructing the Script

      <SCRIPT type="text/javascript">
           loops=3
           num=1
          while (num <= loops)
           {
               document.write("Happy ")
               num=num+1
            }
          document.write("Birthday")
      </SCRIPT>


What You Have Learned


Your Assignment

Here's another challenge. First, type in the program above and make it work. Then modify the program so that you use Prompt to ask the user "How many times do you want Happy to appear before Birthday?" You should capture the response in a variable.

Remember to use Eval() to change the response from text to a number. The program then should write "Happy" as many times as requested.

Here's a possible answer to this assignment
(this will open a new window)


The Concept
The Script
The Script's Effect
Deconstructing the Script
What You've Learned
Your Assignment

On To JavaScript Primer #26