Back

Javascript

Loops

Example 1

Create a new document. Put the code below anywhere in your document. What does numMonkeys do? What does numMonkeys = numMonkeys - 1 do?

<script type="text/javascript">
     var numMonkeys = 10;
     while ( numMonkeys > 0 )
     {
          document.write("<p> "+ numMonkeys + " little monkeys jumping on the bed. " +
          "One fell off and bumped its head. " +
          "Mama frowned and shook her head. Now " +
          (numMonkeys-1) + " little monkeys jumping on the bed.</p>");
          numMonkeys = numMonkeys - 1;
     }
</script>

Example 2

Here's another way to write the same thing. What does numMonkeys = 10 do? What does numMonkeys > 0; do? What does numMonkeys– – do?

<script type="text/javascript">
     for( var numMonkeys = 10; numMonkeys > 0; numMonkeys– – )
     {
          document.write("<p> "+ numMonkeys + " little monkeys jumping on the bed. " +
          "One fell off and bumped its head. " +
          "Mama frowned and shook her head. Now " +
          (numMonkeys-1) + " little monkeys jumping on the bed.</p>");
     }
</script>

Example 3

Here's a new rhyme. Can you write a script that produces the rhyme on your web page? (It's OK if each verse is all on one line on your page.) Hint! You will need to use this: numMonkeys ++

2 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
3 little monkeys jumping on the bed.

3 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
4 little monkeys jumping on the bed.

4 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
5 little monkeys jumping on the bed.

5 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
6 little monkeys jumping on the bed.

6 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
7 little monkeys jumping on the bed.

7 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
8 little monkeys jumping on the bed.

8 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
9 little monkeys jumping on the bed.

9 little monkeys jumping on the bed.
One reached down and grabbed a friend.
Mama sighed and shook her head. Now
10 little monkeys jumping on the bed.