5. Meet the Loops: For, While, and Do...While!


In This Chapter

Learn how to have some code run repeatedly

Work with for, while, and do...while loops


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. You will often never know the number of times you need to run your code. The number of times 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. More than likely, 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 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:

for loops

while loops

do...while loops

Each of these three loop variations enable 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 how to use them.

Onwards!

The for Loop

One of the most common ways to create a loop is by using the for statement to create what is known as 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, so 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;

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

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

If you were to enter this code inside some script tags and preview it in your browser, you will see something similar to what is shown in Figure 5.1.

Image

FIGURE 5.1 The word hello! will be repeated ten times across your page.


Image Note

The words are printed to the browser because we used document.writeln. This is another method we will use (besides alert) that will help us quickly test something out. The document.writeln method takes whatever you want to print as arguments, and when it runs, it replaces everything in the page with the content you were interested in displaying.


This is made possible thanks to the for loop, so we are gonna thank it by learning all about how it works. First, let’s look at 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 form shown in Figure 5.2.

Image

FIGURE 5.2 Our for loop and the three regions that we will focus on.

These three differently shaded 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 Condition

In the first region, we define a starting condition. A common starting condition 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.

Terminating Condition (aka Are we done yet?)

Once we define our starting point, in the next region we determine the terminating condition. That is basically a fancy way of saying how long to keep looping. This is handled by a conditional expression (just like what you say in the previous chapter!) 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 from its starting value of 0. 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 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 terminating point:

for (var i = 0; i < count; 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

Okay, now that we looked at each part of the for statement in great detail, let’s run through it all once more to make sure we totally got this. Our full example, repeated from earlier, is as follows:

var count = 10;

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

function saySomething() {
       document.writeln("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 the statements inside your loop have executed, 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-initialized. Its value is set to the incremented value of 1, and that means it still 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.

Stopping a Loop Early

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:

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.

var floors = 28;

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

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

Going Backwards

There is no reason for why you have to 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 or do a traditional increment/decrement operation:

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. When you “add” letters together as we are doing, the result is a, aa, aaa, aaaa, aaaaa, and so on!

Array! Array! Array!

I know we haven’t looked at arrays in detail yet, but one of the greatest love stories of all time is that between a data structure known as an array and the for loop. The bulk of your time, you will be using loops to travel through all of the data stored in an array, so just glance through the following code and explanation. I’ll rehash this information in greater detail when we formally talk about arrays really soon in Chapter 15, Arrays.

var myArray = ["one", "two", "three"];

for (var i = 0; i < myArray.length; i++) {
    document.writeln(myArray[i]);
}

The TL; DR version is as follows: 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.

Anyway, I figured I would introduce you to the array and for loop pair. Just like two seemingly random characters at the beginning of a Quentin Tarantino movie, their actual contribution to the story seems irrelevant at this point in time.

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 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. Now, just because you can do something doesn’t mean you should. This example falls clearly in the “You shouldn’t do this!” bucket.

The Other Loops

Living in the shadow of the beloved for loop are the while and do...while loop variants. These two loop variants clearly serve a purpose, but I’ve never quite found what that purpose is. Despite that, in the interest of completeness and to familiarize you with code you will encounter in the wild, 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. 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!");
} 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.


Image Tip

Just a quick reminder for those of you reading these words in the print or e-book edition of this book: If you go to www.quepublishing.com and register this book, you can receive free access to an online Web Edition that not only contains the complete text of this book but also features a short, fun interactive quiz to test your understanding of the chapter you just read.

If you’re reading these words in the Web Edition already and want to try your hand at the quiz, then you’re in luck – all you need to do is scroll down!


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.119.170