Working with loops

Looping or iteration control is used to execute some set of instructions repeatedly. Without loops, we would have to write the instructions as many times we want them to execute. Let’s print numbers 1 through 5 without using a loop:

<script language="javascript">
document.write (1 + "<br>");
document.write (2 + "<br>");
document.write (3 + "<br>");
document.write (4 + "<br>");
document.write (5 + "<br>");
</script>

The following shows the output of the above code:

1
2
3
4
5

Before we do this same example with a loop control structure, let’s first point out that there are two types of loops:

  1. loops that repeat a set number of times before quitting. This type of loop is created with a for loop. You can use a for loop when you know exactly how many times you want to execute some code.
  2. loops that repeat until a certain condition is satisfied. This type of loop is created with a while loop. The while is useful for those situation in which it is known how many times a specific code needs to be run.

Loops are fundamental constructs in JavaScript that allow you to execute a block of code repeatedly. Here’s a comprehensive guide to loops and iteration control in JavaScript:

Working with loops

With a for loop, we can run a group of statements a set number of times through the use of a counter, a variable that tracks the number of times the group of statements has been run. To create a for loop, we set an initial value for the counter variable and each time our command block is executed, we change the value of the counter. When the value of the counter variable reaches our stopping value, the loop will end. A general syntax for creating a JavaScript loop is:

for (startingValue, condition, iterationValue) {

JavaScript statements that you want to execute repeatedly

}

where

startingValue = the initial value of the counter variable

condition = a Boolean expression that must be true for the loop to continue and must become false for the loop to stop

iterationValue = a value to change the value of the counter variable

Let’s create a for loop that will print numbers 1 through 5. The following shows the JavaScript code for creating a for loop:

<script language="javascript">
  for (counter=1; counter <=5; counter++) {
    document.write(counter + "<br>");
  }
</script>

On line 2, we start our for loop with the JavaScript keyword for. With counter=1;, we declare a variable called counter and it is set to 1. The purpose of this statement is to set a initial value for our loop. The code counter <=5; is the Boolean expression. The purpose of this code is to stop the for loop after the code inside the for loop has executed 5 times. The counter++ simply adds 1 each time the command inside the loop is executed. The following shows the output of this loop:

1
2
3
4
5

So how did we get this output? Let’s review how the for loop code works. In our example, we start our counter variable with 1. Next, the Boolean expression, counter <=5;, checks if the value of counter is less than or equal to 5. Is it? Yes, because we started our for loop with 1 and it is less than 5. Then, with counter++ we add 1 to counter; so counter will become 2, after the print statement inside the for loop has executed. That will complete our first iteration. At the end of first iteration, the number 1 would be printed to the screen, the value of the counter variable would be 2.

The for loop does not end executing yet because our Boolean expression is still true. Our counter variable is 2, which is less than 5, so the print statement inside the for loop will print 2. Then, the value of counter will be updated again with 1, changing counter variable to 3. The for loop will continue to run like this until the value of counter reaches 6, at which point, the Boolean expression will be false because 6 is not less than or equal to 5. See table 1; it shows the value for the counter variable for each loop iteration. As the table shows, when the counter reaches 6, the for loop will stop because the Boolean expression would no longer be true.

Table 1 for loop execution
IterationCounter valueIs counter <= 5?
First1Yes
Second2Yes
Third3Yes
Fourth4Yes
Fifth5Yes
Sixth6No

In the previous example we incremented the for loop by 1 but we are not limited to incremented by just 1. We can specify other update expressions, as shown in the following for loops:

for (i = 5; i >=1; i--) { document.write (i + " ");}// prints 5 4 3 2 1
for (i = 2; i <= 64; i *= 2) { document.write (i + " ");}// prints 2 4 8 16 32 64
for (i = 1000; i > 10; i /= 5) { document.write (i + " ");}// prints 1000 200 40

In the first for loop, we initialize the variable i to 5 and decrement i by 1, as long as i is greater than or equal to 1. In the second for loop, we use the multiplication operator to update the variable i. Note we could we have rewritten the update expression as i = i * 2 to double the value of i each time for loop is executed while the value of i is less than or equal to 64. In the third loop, we use the division operator in the update expression to divide i by 5, as long as i remains greater than 10.

The while loop

The while loop is different from a for loop in the respect that it is known ahead of time how many times a while loop will execute. Suppose you ask the user for some input, the user may not enter the value you seek in the first try. So using a while loop, we would keep requesting for the right input. But if you use a for loop, you would be limited to asking only once, twice, or however many times you use. The point is with a for loop, you initially specify how many times the for loop is to be executed, but with a while loop that is not necessarily true.

The general syntax for creating a while loop is:

while (condition) {
JavaScript statements that you want to execute repeatedly
}

where
condition = a Boolean expression that can be true or false. While the Boolean expression is true, the JavaScript code inside the while loop is executed.

The following shows an example of a while loop:

<script language="javascript">
var i = 1;
while (i <= 5) {
document.write (i + " ");
i++;
}
</script>

Note that for a while loop we initialize our counter variable, i, before the loop starts. Note also the counter variable is updated inside the while loop. This while loop prints:

1 2 3 4 5

Table 2 shows more examples of while loops and their corresponding output.

Table 2 more examples of while loop in use

JavaScript while loop codeOutput
<script language="javascript">
var i = 1; // this while loop prints odd numbers between 1 and 10. while (i <= 10) {
document.write (i + "<br>");
i += 2;
}
</script>
1
3
5
7
9
<script language="javascript">
var i = 2; // this while loop squares i as long as i is less than or equal to 1024. while (i <= 1024) {
document.write (i + "<br>");
i *= 2;
}
</script>
2
4
8
16
32
64
128
256
512
1024

Infinite loops

When you initially work with loops, you may create infinite loops. An infinite loop executes indefinitely. An infinite loop does not stop executing because the stopping condition is never reached. An infinite loop can freeze your computer, making your computer unresponsive to your commands. To avoid such problems, make sure to properly initialize the counter, make sure the terminating condition is eventually met with the proper updates to the counter variable. As an example, consider the following infinite for loop:

for (j = 100; j >= 5; j++)

Do you know why is this an infinite for loop? Note j is initialized to 100 and each time the loop is executed, we add 1. Thus each time the for loop will execute the value of j will go up by 1, it will never reach 5, our stopping condition.

As you may guess, you could also create an infinite while loop. The following shows how:

<script language="javascript">
var i = 2;
while (i <= 10) {
document.write (i + "<br>");
i -= 2;
}
</script>

In the above while loop, i will always remain less than 10 because each time the loop will be executed, i will be decremented by 2.

Nesting loops

Loops can be nested; meaning one or more loops can be placed inside of another loop. A nesting loop becomes useful, for example, when you want to create a tabular output. The following JavaScript code

<script language="javascript">
var sout;
sout = "<table border='1' width='300' cellspacing='0' cellpadding='3'>"
for (i = 1; i <= 10; i++) {
sout = sout + "<tr>";
for (j = 1; j <= 10; j++) {
sout = sout + "<td>" + i * j + "</td>";
}
sout = sout + "</tr>";
}
sout = sout + "</table>";
document.write (sout);
</script>

prints a multiplication table as:

12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100

How did we produce such a table? Well, our code uses two for loops to produce that table. Before we say more about the loops, let’s start reviewing from the beginning of the code. If line 3, sout = “<table border=’1′ width=’300′ cellspacing=’0′ cellpadding=’3’>”, looks strange to you, let’s explain what it does. With this line, all we are saying is that we want to create a HTML table. Note how the value for each of the table properties (such as border, width, cellspacing, and cellpadding) is enclosed by single quotation marks. (Recall that a table tag creates a table in HTML.)

We could have used a document.write statement instead of using a variable to hold our output message. It is actually more efficient to use a variable for output instead of repeatedly calling the document.write() method. So, in this example, each time we want to print something to the web page, we simply assign the output to the variable sout. Note the use of the “+” operator to add a string to the previous value of the sout variable.

Line 4 has our first for loop; we could refer to this loop as an outer loop. It is an outer loop, as the name implies, because it inside contains a loop. The loop inside an outer loop is called an inner loop, see line 6.

Let’s now describe what is happening inside the loops, lines 4 through 8. Basically, the outer for loop starts to execute first and it will execute 10 times – creating total of 10 rows. However, for each time the outer loop is executed, the inner loop will execute 10 times – creating 10 columns or cells in each row. Thus the first time the outer loop executes, sout = sout + “<tr>”; will create our first row; the first time the inner loop executes, we create our first table cell with 1 * 1 = 1. The second time the inner loop executes, the second cell is created with the value 2; then the third cell is created with the value of 3, and so on. When inner loop stops executing when j reaches 10, the first row is filled with 10 cells. Finally, sout = sout + “</tr>”; ends our first row. Similarly, remaining rows and cells are created.

We can also use a while loop to create nested loops. See the following code that produces the same output as you saw with the nested for loop:

<script language="javascript">
var sout, i, j;
sout = "<table border='1' width='300' cellspacing='0' cellpadding='3'>";
i = j = 1;
while (i <= 10) {
sout = sout + "<tr>";
while (j <= 10) {
sout = sout + "<td>" + i * j + "</td>";
j++;
}
sout = sout + "</tr>";
j = 1;
i++;
}
sout = sout + "</table>";
document.write (sout);
</script>

On line 4, i = j = 1;, we assign the value 1 to i and j. In this statement, 1 is first assigned to j and then the value of j, 1, is assigned to i. On line 5, our outer loop starts here. Line 6 is responsible for creating one row at a time, each time the outer while loop executes. The inner loop creates 10 cells each time the outer loop executes. The following shows the output:

12345678910
2468101214161820
36912151821242730
481216202428323640
5101520253035404550
6121824303642485460
7142128354249566370
8162432404856647280
9182736455463728190
102030405060708090100