JavaScript Tutorial 15
while and for loops
You've learned the first, and most used statement, 'if'. The next most commonly used statements are loop statements. Loop statements repeat commands (known in the programming world as iteration) over and over again as many times as you specify. "I don't get it," you say? No problem, let's look at a real life example of when you would use a loop like process.
Let's say that you're on the bomb squad, and you're told there's a bomb in an old house. You're told that the bomb is under the sixth step of a staircase and if you step on the sixth stair, the bomb will go off. You're smart, so you know that you need to stop before the sixth stair. But, let's say you're not smart:
Click Here to see what happens.
As you can see, the you weren't careful to check when you had gone too far. But, if the you had used the concept of a loop, this wouldn't have happened.
Click Here to see what I mean.
Did you see in the text area at the top where the you were counting each step that you were on? Well, if not, go back and look. If you did, or at least you have now noticed, you know what you were doing. You were counting the steps that you climbed so
that you would know when you were at stair '5' and knew that you should stop. That's a loop!! You repeated the command of take a step until you were at stair '5', which was the highest stair you could be on without blowing up.
So, the thought process was:
- Is it safe to step to the next stair?
- If it is safe, take a step (this is the command).
If we were to think of this process as programmers, our script would look something like this (this is not the correct JavaScript syntax for this process, you will learn that in a second - use this only for thought organization):
Loop this stuff
if I am not on step 5 yet
take a step
End Loop
|
Now, let's learn how to use loops in JavaScript. There are 2 types of loops, 'for' and 'while'. Let's start with the while loop since it's syntax is a little more simple.
The While loop statement is another of the most powerful tools at your disposal. It causes a series of commands to repeat a number of times that you specify. Let's start by doing a simple 'While' loop. Make your document look like this:
Click here to maximize
<html>
<head>
<title>
(Your title)
</title>
<script language=javascript>
<!--
function doIt(){
check = "go";
window.document.exampleform.output.value = "";
while (check == "go"){
window.document.exampleform.output.value += "z";
if (window.document.exampleform.output.value.length == 50){
check = "stop";
}
}
}
//-->
</script>
</head>
<body bgcolor=white>
<form name=exampleform><br>
<input type=test name=output size=60><br>
<input type=button onclick=doIt() value='Do It'>
</form>
</body>
</html>
|
What this script does is, when the 'Do It' button is clicked, the
script will display 50 z's in the text input. Click 'Preview' and try
it.
Now let's analyze how it works. Look at this:
<html>
<head>
<title>
(Your title)
</title>
<script language=javascript>
<!--
function doIt(){
check = "go";
window.document.exampleform.output.value = "";
while (check == "go"){
window.document.exampleform.output.value += "z"; \
if (window.document.exampleform.output.value.length == 50){
check = "stop";
}
}
}
//-->
</script>
</head>
|
The first thing we need to look at is the stuff in blue. As I'm sure you already know, we are defining a variable. This variable will be used by our loop as you will soon see. The white line makes the text input on your page go blank before we start our loop and fill it back up again.
The green line is the first part of our loop. The 'while' portion tells the browser that we are defining a 'while' loop. Next comes the test clause, which just as in an 'if' statement, performs a test. With while loops, the test being performed decides
whether or not the loop should perform a set of commands - just as in an 'if' statement. If this test clause returns true, the commands are executed. Then you see an open bracket ({). You guessed it - that's how we tell the browser that we are about to begin defining commands that are to be executed every time the 'while' loop iterates.
Next - in purple - is the first command to be executed. This line takes whatever value is currently in the text field, and adds a 'z' to the end of it.
In red we are testing to see if the length of the string contained in the text field is '50' yet. If it is, we set the check variable to 'stop'.
Finally, the green close bracket (}) tells the browser that the set of commands for the loop have been concluded.
So, you know what all we did. Now here's how it works:
First, we initialized the check variable to equal 'go'. Then, when the test clause of the while loop tested the value of check it found that it did indeed equal 'go', so it executed the commands defined. When the commands were completed and the while loop reached its closing bracket, it ran the test clause again.
This continued 50 times until eventually the length of the string in the text field was '50', at which point, the embedded 'if' statement changed the value of check to 'stop'. The next time the test clause was run, it returned false, and the while loop stopped. Get it?
So, in conclusion, the while loop is very useful when iterating a set of commands using string or logical values for a test.
The 'for' loop is very similar - but it is mostly useful for when you are using numbers that increment. Make your document look like this:
Click here to maximize
<html>
<head>
<title>
(Your title)
</title>
<script language=javascript>
<!--
function doIt(){
window.document.exampleform.output.value = "";
for (x = 1; x < 50; x++){
window.document.exampleform.output.value += "z";
}
}
//-->
</script>
</head>
<body bgcolor=white>
<form name=exampleform><br>
<input type=test name=output size=50><br>
<input type=button onclick=doIt() value='Do It'>
</form>
</body>
</html>
|
Go ahead, try it. It should do exactly the same thing. Let's look at the syntax for the 'for' loop (let's analyze only the for loop to keep it simple):
for (x = 1; x < 50; x++){
window.document.exampleform.output.value += "z";
}
|
The 'for' loop does exactly the same thing as the 'while' loop. The only difference is syntax and what it is best at. As you see in red, the only real difference is the test clause. You will notice the addition of two things there. In fact, they aren't new, they're just in a different place.
We know ahead of time that we are going to add exactly '50' z's to our string. '50' is a number, so we have decided to use a for loop because I told you that it is best for testing numbers that increment.
The 'x = 1;' part (notice the semi-colon) set the value of x to zero at the beginning of the loop. This is just like when we set the value of check to 'go', except in this case, we are telling the browser to start counting with '1'.
The second part - 'x < 50;' - holds the actual test (in this case, it is testing how many z's we have added to the text field). When 'x' is equal to or greater than 50, the loop will stop.
Finally, 'x++;' runs each time the loop's commands end, incrementing 'x'. This is just like when we used the 'if' statement to test how long the string was and change check if we had already inserted '50' z's, except that we are doing this every time the loop runs and gradually the value of 'x' gets closer to '50'.
You must have a semi-colon (;) in between each of these to tell the browser that you are moving on to another part of the for loop definition.
That wasn't hard, now was it?
Now, remember a few minutes ago when I told you that the while loop was only good for testing string and logical values? I kinda lied. We could have used a while loop in this case, but the for loop would have been typed faster, so it was a better choice. If we had wanted to use a while loop, we would have done this (type this):
Click here to maximize
<html>
<head>
<title>
(Your title)
</title>
<script language=javascript>
<!--
function doIt(){
window.document.exampleform.output.value = "";
x = 1;
while (x < 50){
window.document.exampleform.output.value += "z";
x++;
}
}
//-->
</script>
Leave the rest
|
Does exactly the same thing, the stuff is just re-arranged. As I'm sure you agree, the for loop doesn't really save any typing, but for some reason, it seems easier to do when doing a test like this. It's really up to you which you prefer. I think for is more organized.
Do you remember back in the last tutorial when we nested one 'if' statement within another? Well, you can nest any statement within any other statement. In fact, when you are using loops, you most often will nest another statement within the loop.
Here's an example:
Click here to maximize
<html>
<head>
<title>
(Your title)
</title>
<script language=javascript>
<!--
function doIt(){
comma = ", ";
outputvalue = "";
window.document.exampleform.oddoutput.value = "";
window.document.exampleform.evenoutput.value = "";
for (x = 1; x <= 10; x++){
testvalue = x / 2 - Math.floor(x / 2);
if (testvalue == 0){
window.document.exampleform.evenoutput.value += x + comma;
}
else{
window.document.exampleform.oddoutput.value += x + comma;
}
}
}
//-->
</script>
</head>
<body bgcolor=white>
<form name=exampleform><br>
Odds: <input type=test name=oddoutput size=50><br>
Evens: <input type=test name=evenoutput size=50><br>
<input type=button onclick=doIt() value='Do It'>
</form>
</body>
</html>
|
Guess what this is going to do. I'll give you a hint. The phrase "testvalue = x / 2 - Math.floor(x / 2);" uses one of the methods that you will learn about later to test the value of 'x'. If the value of 'x' is odd, 'testvalue' will equal '0.5'. If 'x
' is even, 'testvalue' will equal '0'. Do you know what this script does yet?
Go try it.
Here's what it did. If the value of 'x' was odd, it's value was added to the "Odds" text field. Otherwise, it was added to the "Evens" text field. Then the loop ran again for the next value of 'x'. Neat huh?
This concept of nesting statements works with any statement. That is, you can nest one or more 'if' statements within a loop, you can nest one or more loops within a loop, or vice versa.
You can also have multi-tiered nests. That is, you can nest a loop within a loop that is also nested within a loop, and so on.
|