For, While, and Do...While Loops in JavaScript

by kirupa   |   4 March 2014

When you are coding something, there will be times when you want to repeat an action or run some code multiple times. For example, let's say we have a function called saySomething that we want to repeatedly call 10 times.

One way we could do this is by simply calling the function 10 times using copy and paste:

saySomething();
saySomething();
saySomething();
saySomething();
saySomething();
saySomething();
saySomething();
saySomething();
saySomething();
saySomething();

This works and accomplishes what we set out to do, but...you shouldn't do something like this. Duplicating code is never a good idea.

Now, even if you decide to duplicate some code a few times manually, this approach doesn't really work in practice. The number of times you will need to duplicate your code will vary based on some external factor such as the number of items in a collection of data, some result from a web service call, the number of letters in a word, and various other things that will keep changing. It won't always be a fixed number like 10. Often, the number of times you want to repeat some code could be very VERY large. You don't want to copy and paste something a few hundred or thousand times in order to repeat something. That would be terrible.

What we need is a generic solution for repeating code with control over how many times the code repeats. In JavaScript, this solution is provided in the form of something known as a loop. There are three kinds of loops you can create:

Each of these three loop variations allow you to specify the code you want to repeat (aka loop) and a way to stop the repetition when a condition is met. In the following sections, you'll learn all about them.

Onwards!

The for Loop

One of the most common ways to create a loop is by using the for statement to create a for loop. A for loop allows you to repeatedly run some code until an expression you specify returns false. That probably doesn't make a whole lot of sense. To help clarify this definition, let's look at an example.

If we had to translate our earlier saySomething example using for, it would look as follows:

var count = 10;

for (var i = 0; i < count; i++) {
	saySomething();
}

function saySomething() {
	document.writeln("hello!");
}

If you were to enter this code inside some script tags and preview in your browser, this is what you would see:

hello! hello! hello!

The word hello! will be repeated ten times across your page. This is made possible thanks to the for loop, so we are gonna thank it back by learning all about how it works. First, here is our star:

for (var i = 0; i < count; i++) {
	saySomething();
}

This is a for loop. It probably looks very different from other statements you've seen so far, and that's because...well, it is very different. To understand the differences, let's generalize a for loop into the following form:

for (start_point; expression; going_from_start_to_finish) {
  // code to execute
}

This high-level view corresponds to the actual values from our example:

for (var i = 0; i < count; i++) {
  saySomething();
}

These three differently colored regions each play a very important role in how your loop functions. In order to use a for loop well, we must know what each region accomplishes. That brings us to...

The Starting Point

In the first region, we define a starting point. A common starting point usually involves declaring and initializing a variable. In our example, I create a new variable called i and initialize it to the number 0:

for (var i = 0; i < count; i++) {
  saySomething();
}

In case you are wondering, the variable name in these cases is traditionally a single letter...with i being the most common. The value you initialize this variable to is also traditionally 0. There is one really good reason for using 0, and I'll explain that reason a bit later.

How Long to Keep Looping

Once we define our starting point, in the next region we determine how long to keep looping. This is handled by an expression that returns either true or false. In our example, the condition is that our i variable is less than the value of count - which is 10:

for (var i = 0; i < count; i++) {
  saySomething();
}

If our i variable is less than 10, this expression evaluates to true and our loop continues to run. If our i variable becomes equal to or greater than 10, the condition is false, and our loop terminates. Now, you may be wondering what causes our i variable to actually change. Well, that is covered next...

Reaching the End

So far, we've looked at our starting point. We also looked at the expression that needs to be evaluate to false if we want to break our loop. What is missing is the final region where we describe how to go from your starting point to the stopping point:

for (var i = 0; i < 25; i++) {
  saySomething();
}

In our example, at each iteration of our loop, we increment our i variable by 1. In case you aren't familiar with this syntax, the ++ after i means you increase whatever value the i variable had by 1. Each time our loop runs, whatever you specified here will execute. In this case, our i value will increment.

Putting It All Together

Ok, now that we looked at each part of the for statement in greater detail, let's run through it all at once to see what is going on. Our full example, repeated from earlier, is as follows:

var count = 10;

for (var i = 0; i < count; i++) {
	saySomething();
}

function saySomething() {
	document.write("hello!");
}

When our for loop is initially hit, the i variable is created and initialized to 0. Next, our code checks if the value of i is less than the value referenced by count...which is 10. At this point, everything is green and whatever code is inside the loop executes. In our case, that is the saySomething function. Once that is done, the last part of the for statement kicks in. The i variable is incremented by 1.

Now, the loop starts all over again except the variable i isn't re-initailized. It's value is 1, and that means it passes the i < count test. The saySomething function is called again, and the value of i is incremented again. Now, the i variable's value is 2.

This whole process repeats until the value of i equals 10. At this point, the i < count test will fail and the loop will exit after having successfully executed the saySomething() function 10 times.

Some for Loop Examples

In the previous section, we dissected a simple for loop and labeled all of its inner workings. The thing about for loops and most everything in JavaScript is that a simple example doesn't always cover everything you might need. The best solution is to look at some more examples of for loops, and that's what we are going to be doing in the next few sections.

Breaking a Loop

Sometimes, you may want to end your loop before it reaches completion. The way you end a loop is by using the break keyword. Below is an example:

for (var i = 0; i < 100; i++) {
    document.writeln(i);

    if (i == 45) {
        break;
    }
}

When the value of i equals 45, the break keyword stops the loop from continuing further. While this example was just a little bit contrived, when you do run into a real-world case for ending your loop, you now know what to do.

Skipping an Iteration

There will be moments when you want your loop to skip its current iteration and move on to the next one. That is cleverly handled by the continue keyword:

var floors = 28;

for (var i = 1; i <= floors; i++) {
    if (i == 13) {
        // no floor here
        continue;
    }

    document.writeln("At floor: " + i + "<br>");
}

Unlike break where your loop just stops and goes home, continue tells your loop to stop and move on to the next iteration. You'll often find yourself using continue when handling errors where you just want the loop to move on to the next item.

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.

Array! Array! Array!

One of the greatest love stories of all time is that between a data structure known as an array and the for loop:

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

An array is a collection of items. The way to enumerate and access all of the items in an array requires some sort of a loop, and the for loop is usually the chosen one.

We're Jumping Ahead Here :(

I know we haven't looked at arrays in detail yet, so just glance through the code and the explanations if you aren't too familiar with them. I'll rehash some of this information when we formally talk about arrays in the future.

Notice that my condition for how long we loop involves the array's length (myArray.length) as opposed to some fixed value like 10. Also, the first item in an array is referenced by the number 0. In fact, almost all first items in JavaScript are referenced by a 0. That is why we initialize our loop counter, the i variable, to 0 as opposed to 1 or some other value.

Anyway, I figured I would introduce you to the array and for loop pair. How romantic!

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.

The Other Loops

Living in the shadow of the beloved for loop are the while and do...while loop variants. These two loops variants clearly serve a purpose, but I've never quite found what that purpose is. Despite that, in the interest of completeness, let's quickly look at both of them.

The while Loop

The while loop repeats some code until its test condition (another expression) returns false:

var count = 0;
       
while (count < 10) {
    document.writeln("looping away!");

    count++;
}

In this example, the condition is represented by the count < 10 expression. With each iteration, our loop increments the count value by 1:

var count = 0;
       
while (count < 10) {
    document.writeln("looping away!");

    count++;
}

Once the value of count becomes 10, the loop stops because the count < 10 expression will return false. That's all there is to the while loop.

The do...while Loop

Now, we get to the Meg Griffin of the loop variants. That would be the do...while loop whose purpose is even less defined than while. Where the while loop had its conditional expression first before the loop would execute, the do...while loop has its conditional expression at the end.

Here is an example:

var count = 0;

do {
    count++;

    document.writeln("I don't know what I am doing here! <br>");
} while (count < 10);

The main difference between a while loop and a do...while loop is that the contents of a while loop could never get executed if its conditional expression is false from the very beginning:

while (false) {
    document.writeln("Can't touch this!");
}

With a do...while loop, because the conditional expression is evaluated only after one iteration, your loop's contents are guaranteed to run at least once:

do {
    document.writeln("This code will run once!");
} while (false);

Yaaawwn! Anyway, there is just one last bit of information I need to tell you before we move on. The break and continue statements that we saw earlier as part of the awesome for loop also work similarly when used inside the while and do...while loop variants.

Conclusion

So there you have it - a look at for loops and how you can use them along with very basic coverage of the while and do...while loops. Right now, you may not see yourself using loops a whole lot. As we start getting into more involved situations involving collections of data, elements in your DOM, text manipulation, and other stuff, you'll be using loops a whole lot more.

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!!!