Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat.

free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class">

Free Web tutorials covering HTML, CSS, JavaScript, and DHTML from beginner to advanced. Free downloads and developer resources. Personalized help via email, form, and chat. free, web, tutorials, HTML, html, CSS, css, stylesheet, cascading stylesheet, Javascript, javascript, JavaScript, DHTML, dhtml, beginner, advanced, web development, web page, web site, free web tutorial, free HTML tutorial, free CSS tutorial, free css tutorial, free cascading stylesheet tutorial, free stylesheet tutorial, free javascript tutorial, free DHTML tutorial, free HTML class, free CSS class, free stylesheet class, free cascading stylesheet class, free javascript class, free DHTML class

<Code_Punk>'s

Advanced JavaScript Lesson 10:
FOR Loops

Code Tutorials



Site Development



Downloads



Help!!



Home

The FOR Loop

Let's begin by making the array we used in the previous lesson.

<script language="JavaScript">

names = new Array ("john","martha","george","andy");

</script>

Well, okay, I shortened the array's name to "names" instead of "names_array". But, you should be able to recognize the above.

Lets say we want to display these names, in order, on your page. We could use "document.write()" like this:

<body>
<script language="JavaScript">

document.write(names[0] + "<br>" + names[1] + "<br>" + names[2] + "<br>" + names[3]);

</script>
</body>

Boy, that's a mess, huh. It'd be easier just to display the names using plain old HTML. But, because these names are in an array, we can use a loop and simplify writing the names.

A simple loop, like the one we want, can best be made using JavaScript's "FOR" statement:

<body>
<script language="JavaScript">

for (counter = 0; counter < names.length; counter++){

document.write(names[counter] + "<br>");
}

</script>
</body>

Check out the above code in action here.

Lots of new stuff to talk about here. For now let me just give you an overview. We've made a FOR loop that begins at zero and counts by 1. That is, it counts in increments of one -- 0,1,2,3... It will stop when "counter" is no longer less than the "names" array's length.

While this loop is counting, it does whatever you tell it to in the curly braces -- { }. In this case, we've told it to write the name and make a line break. The loop automatically goes through all of the names in the array.

Using "counter" as a dynamic number in the "names[counter]" reference, is what makes the loop effective. This may not seem like much with our small array, but imagine you had over 100 names. This code can save a lot of HTML or unlooped JavaScript code.

An Overview

You'll be coding a lot of FOR loops, especially when dealing with arrays, and you should get very familiar with them. There are two main sections to a FOR loop. First, there is the term "for" and the conditions that control the loop in parentheses.

Secondly, there are a pair of curly braces. The statements put in these curly braces will be repeated as the loop runs. Each pass a loop makes is called an iteration of the loop.

The conditions under which the FOR loop runs are put inside the parentheses and separated by semicolons (;). There are three conditions that need to be defined:

Declare the counter variable. This is the variable used to hold the number of the current iteration of the loop. When used with array objects, it is generally given an initial value of zero for the first object. You don't need to declare this variable outside of the loop with a "var" statement. In fact, you don't use "var" inside the parentheses either. You can use any variable name you'd like. I used "counter". Many loops use "i" for "increment".

The "Halt Condition". The second section of the FOR's conditions tells the loop when to stop. In our case, the loop will only run as long as "counter" is less than the arrays length. It will stop when "counter" equals (or is greater than) "names.length". In our example this means it would stop when the counter variable gets to 4.

Incrementation. Incrementation is the last thing in the parentheses. It tells the loop what to count by. In our case we're counting by 1, but you could count by 2, 3, or any other increment.

Below are more detailed descriptions of the three conditions you'll need to code in your FOR loops.

The Counter

for (counter=0; counter < names.length; counter++){
statements to run in the loop
}

The key behind making a FOR loop useful is making and using a "counter". A counter is just a variable set up to change as the loop progresses. I called mine "counter", but you can use any variable name you'd like.

These counters are variables, but do not need a "var" statement to declare them. They are declared in the first part of the FOR statement's condiditons and initialized to a value. I've initialized "counter" to zero. That means it's first value when the loop is run will be 0. You can initialize this variable to any value you need.

The important thing about "counter" is that its value changes as the loop is run. This dynamic value can be used to cycle through the objects of an array.

Incrementation

for (counter=0; counter < names.length; counter++){
statements to run in the loop
}

To make things clearer, I've jumped to the last part of the FOR statement's conditions -- incrementation. This sets the type of counting the loop will do. The "counter++" is the same as using "counter = counter + 1". This means "counter's" value will increase by 1 each time the loop is run.

You could just use "counter = counter + 1". The "counter++" is just coding shorthand for the same thing. You could also just as easily count by 2's or 3's: "counter = counter + 2" or "counter = counter + 3". The shorthand "counter++" only works for 1.

Generally and increment of 1 is used. Our current loop will give "counter" and initial value of 0 and increase that amount by 1 with each iteration of the loop.

The Halt Condition

for (counter=0; counter < names.length; counter++){
statements to run in the loop
}

The "halt condition" tells the loop when to quit running. This almost always uses the counter variable compared to some outside numerical value. In our case we want the loop to run until the last name has been written.

Running Backwards

When designing a FOR loop start with declaring and initializing the counter. Then figure out the incrementation and, finally, when you want the loop to terminate (halt). Let's practice by making our array write the names in reverse order.

The list on the right of the example were generated by reversing the loop.

First lets think of a variable, I'll be using "counter" again. What should we initialize it to? We want to begin with the last name in the array and count backwards to the first one.We have the array's length to help us again. The last object's number will always be 1 less than the array's length. Remember that the objects are numbered beginning with zero and that length is counted beginning with 1. We can set up our counter using "names.length - 1" to refer to the last object in any array:

for (counter = (names.length - 1);...)

Notice that I put the "names.length - 1" in a nested set of parentheses. They aren't really needed in this case, but it's a good habit to get into. A lot of math can be put in FOR loop conditions and nested parentheses keep the order of calculations straight.

Now that we've gotten the loop to start at our last array object, we need it to count backwards by 1. That would be "counter = counter - 1". There's a shorthand for this, too. It's "counter--".

for (counter = (names.length - 1); ...; counter = counter -1)

I used the longer form for incrementation, but you might rather use "counter--" to impress your friends. Now we need to figure out when we want the loop to stop. We want it to stop after writing the last name which is "names[0]". So, we don't want "counter" to be less than zero:

for (counter = (names.length - 1); counter < 0; counter = counter -1)

Now we have the FOR conditions defined. The counter will have an initial value equal to the number associated with the last array object. The loop will count backwards by 1 until "counter's" value is less than zero, or less than the first array object's number. All we have to do now is use "counter" in the statements we want looped, or repeated. We've been using "document.write()".

for (counter = (names.length - 1); counter < 0; counter = counter -1){
document.write(names[counter] + "<br>");
}

Don't foget the curly braces -- { } ! All of the statements you want looped must be inside the FOR statement's curly braces.

When the loop has met its "halt condidition" and stops, any statements coded after (below) the loop's closing brace will be run. If there are no further statements, as in our case, things just stop and everything's done.

Summary & Exercises

You can use the FOR statment to make a loop that will repeatedly run a single set of processes on multiple array objects.

A FOR statement has three conditions that must be set. The first is declaring the counter variable. This variable should be set to the first number to be used in the loop.

The second condition is when the you want the loop to stop. This generally entails comparing the counter variable to some outside number like array_name.length. Conditions are put in parentheses and separated by semicolons ( ; ).

The final condition is incrementation. This is how the loop counts. Most loops count by 1 using "counter_variable++" or "counter_variable--". Other conditions can be expressed in the form "counter = counter +/- increment".

Try making a longer array, 12 or more strings, and using a FOR loop to display the strings. You might want to try assinging objects to the array directly: "names[8] = "benny"". Try using different increments to get your loop to count every second or third name.



To Next Advanced JavaScript Lesson

Back To Advanced JavaScript Index