Introducing JavaScript Functions and Loops - Loops
(Page 3 of 4 )
Another way for programmer's to be lazy is with loops. Loops are used when you want to repeat a task several times. There are two types of loops in JavaScipt: the For Loop and the While Loop.
For Loop
For Loops are used when you wish to define how many times you want to loop a certain code. Here is a program that counts down the number of beer bottles on a wall.
<html>
<body>
<script type="text/javascript">
for (i = 5; i >= 1; i--)
{
document.write(i + " Bottles of beer on the wall")
document.write("<br />")
}
</script>
</body>
</html>
This code would result in the following print out:
5 Bottles of beer on the wall
4 Bottles of beer on the wall
3 Bottles of beer on the wall
2 Bottles of beer on the wall
1 Bottles of beer on the wall
The For loop takes place in the line: for (i = 5; i >= 1; i--). Let's take a look at what each section does.
The i = 5 assigns the value of 5 to our counter variable. Next, we use the i >= 1 to tell the loop to continue looping while the value of i is greater than or equal to 1. Finally, we use i-- to decrease the value of i by 1 each time through the loop. You could of course also write a loop where you used the increment operator instead of the decremental operator.
Note that it isn't necessary to name the counter variable i. You can name it whatever you like; it is simply programming practice to write i.
Before we go on to the While loop, let's look at one more cool kind of code:
<html>
<body>
<script type="text/javascript">
for (i = 1; i <= 6; i++)
{
document.write("<h" + i + ">I'm shrinking!")
document.write("</h" + i + ">")
}
</script>
</body>
</html>
With this code, we use the header tag to make our text appear to shrink each time through the loop. The result is this:
I'm shrinking!
I'm shrinking!
I'm shrinking!
I'm shrinking!
I'm shrinking!
I'm shrinking!
If we wanted to reverse it, we could use this code:
<html>
<body>
<script type="text/javascript">
for (i = 6; i >= 1; i--)
{
document.write("<h" + i + ">I am becoming the world's fattest man!")
document.write("</h" + i + ">")
}
</script>
</body>
</html>
The result would be:
I am becoming the world's fattest man!
I am becoming the world's fattest man!
I am becoming the world's fattest man!
I am becoming the world's fattest man!
I am becoming the world's fattest man!
I am becoming the world's fattest man!
Next: While Loop >>
More JavaScript Articles
More By James Payne