For Loops in JavaScript

by kirupa   |   15 April 2012

  Have questions? Discuss this HTML5 / JavaScript tutorial with others on the forums.

By default, your code will run only once each time it is called. A lot of times, you will want your code to execute more than once independent of you calling it multiple times. Doing something like what I'm showing below isn't considered good practice:

doSomething();
doSomething();
doSomething();
doSomething();
doSomething();
doSomething();

In fact, I am going to go further and just tell you not to do that :P

Even if you decide to duplicate some code a few times by manually copying and pasting it, the number of times may be arbitrary. Rarely will you want to loop your code a static number of times. More likely, the number of times you will loop your code will vary and depend on other things related to what you are doing.

What we need is a generic solution for looping through our code. We need a solution that starts looping our code and stops looping our code reliably. What we need is...the for statement.

The For Statement

The solution to the problem we are trying to solve is the for statement. Without diving into details, the for statement looks as follows:

for (start; how_long_before_stopping; start->stop) {
// code to execute
}

This high-level view will make more sense when I replace the colored text with actual values:

for (var i = 0; i < 25; i++) {
// code to execute
}

The way a for loop works is pretty simple. The for loop asks you this simple question:

For how long do you want me to loop this code?

The colored regions you fill out every time you use a for loop help answer this question. Let's look at that in greater detail.

The Starting Point

First, what we need to do is define a starting point. A common starting point is 0. In my example, I create a new variable called i and initalize it to the number 0:

for (var i = 0; i < 25; i++) {
// code to execute
}

As I will show in some examples later, you can be creative in your starting point.

How Long to Keep Looping

Once you define a starting point, you need to determine how long to keep looping. This will need to be a condition that returns either true or false. In our example, the condition is that our i variable is less than 25:

for (var i = 0; i < 25; i++) {
// code to execute
}

If our i variable is less than 25, the condition is true and our loop continues to run. If our i variables becomes equal to or greater than 25, the condition is false, and our loop terminates.

Reaching the End

So far, we've looked at our starting point. We also looked at the condition that needs to be me met if we want to break our loop. What is missing is how to go from your starting point to the stopping point. That is covered by the last part:

for (var i = 0; i < 25; i++) {
// code to execute
}

In our example, at each iteration of our loop, we increment our i variable by 1. After running the loop enough number of times, your i variable will eventually have a value of 25. At this point, the condition that keeps our loop intact will no longer hold true. Your i variable will no longer be less than 25, so the loop ends.

Some Examples

In the previous section, you received an anatomy lesson dissecting a simple loop created using the for statement. For the most part, that is all you need to start using them and being productive with looping.

For statements can be varied, and you may find yourself needing to use a variation of it for your particular situation. In this section, I will provide a handful of simple variations from what you've seen just to give you an idea of what is possible.

Array! Array! Array!

One of the most common uses for a for statement is to loop through items in an array:

var myArray = ["one", "two", "three"];
 
for (var i = 0; i < myArray.length; i++) {
document.writeln(myArray[i]);
}

Notice that my condition for how long I loop is involves the array's length (myArray.length) as opposed to some fixed value like 25.

For performance benefits when working with really large arrays, you can cache the value of myArray.length:

var myArray = ["one", "two", "three"];
var arrayLength = myArray.length;
 
for (var i = 0; i < arrayLength; i++) {
document.writeln(myArray[i]);
}

This avoids you having to look-up the length each and every time your loop is running. Instead, you use the much quicker arrayLength variable which gives you access to the stored length value.

Going Backwards

There is no reason for why you have start at 0 and then increment upward:

for (var i = 25; i > 0; i--) {
document.writeln("hello");
}

You can just as easily start high and then decrement until your loop condition returns a false.

You may have heard that doing something like this increases your loop's performance. The jury is still out on whether decrementing is actually faster than incrementing, but feel free to experiment and see if you notice any performance benefits.

You Don't Have to Use Numbers

When filling out your for loop, you don't have to only use numbers:

for (var i = "a"; i !="aaaaaaaa"; i += "a") {
document.writeln("hmm...");
}

You can use anything you want as long as your loop will eventually hit a point where it can end. Notice that in this example I am using the letter a as my currency for running this loop.

Oh No He Didn't!

Oh yes! Yes I did. I went there, took a picture, posted on Facebook, and came back:

var i = 0;
var yay = true;
 
for (; yay;) {
if (i == 10) {
yay = false;
}
i++;
document.writeln("weird");
}

You don't have to fill out the three sections of your for loop in order to make it work. As long as, in the end, you manage to satisfy the loop's terminating condition, you can do whatever you want...just like I did.

Conclusion

So there you have it - a look at for loops and how you can use them. After that last example, I am not sure there is anything more for me to say here.

Getting Help

If you have questions, need some assistance on this topic, or just want to chat - post in the comments below or drop by our friendly forums (where you have a lot more formatting options) and post your question. There are a lot of knowledgeable and witty people who would be happy to help you out

Share

Did you enjoy reading this and found it useful? If so, please share it with your friends:

If you didn't like it, I always like to hear how I can do better next time. Please feel free to contact me directly via e-mail, facebook, or twitter.

Kirupa Chinnathambi
I like to talk a lot - A WHOLE LOT. When I'm not talking, I've been known to write the occasional English word. You can learn more about me by going here.

Add Your Comment (or post on the Forums)

blog comments powered by Disqus

Awesome and high-performance web hosting!
BACK TO TOP
new books - yay!!!