Javascript Loops (Iteration Control) Tutorial

In this Javascript tutorial we learn how to loop sections of code with the for, while and do while loops to control the flow of our applications.

What is iteration control

Javascript allows us to control the flow of our application even further by looping through sections of code.

As an example, let’s consider a database of users that are subscribed to a mailing list.

Normally, we would enter a user’s email address, copy-paste a predefined message, and then send the email.

However, there could be tens of thousands of users in that list. We would need a way to automate the process.

Iteration control allows us to set up that process in code, then repeat it by looping through all the users on the list, sending them each an email.

Javascript provides us with five different kinds of loops:

  • for - This loop iterates through a section of code a set number of times.
  • for in - This loop iterates through the properties of an object.
  • for of - This loop iterates through the values of an iteratable object.
  • while - This loop iterates through a section of code while a condition is true.
  • do while - This loop is the same as the while loop but with a single forced loop at the start.

We will only cover the for, while and do while loops in this tutorial because we haven’t learned about objects yet. We cover the for in and for of loops in later sections.

The while loop

A while loop is used when we don’t know how many times a loop will repeat, like the number of users in a database.

A while loop will keep looping through its code while a specified condition is true. For example: while there are users in a database, loop through the section of code.

To write a while loop, we use the keyword while , followed by the condition in between parentheses and a code block that contains the code we want to execute on each iteration.

Syntax:
while (condition) {

  // execution statement(s)
}
Example:
<script>

  var i = 1;

  while (i <= 10) {

    document.write("Iteration no: ", i, "<br>");
    i++;
  }

</script>

When we run the example above, we should see the following output.

Output:
Iteration no: 1
Iteration no: 2
Iteration no: 3
Iteration no: 4
Iteration no: 5
Iteration no: 6
Iteration no: 7
Iteration no: 8
Iteration no: 9
Iteration no: 10

The single section of code we wrote in the code block was repeated 10 times.

Let’s break down the example above step by step.

  1. First, we set up a variable called i with the number 1. This variable will act as a counter and help us to see which iteration of the entire loop we’re on.
  2. Then, we specify our condition. While the number in i is less than or equal to 10, execute the code in the code block.
  3. In the code block we have a simple statement that prints the number in i. We also increment i by one by adding ++ to it.

What will happen is the following:

  1. The translator will see that i is 1. This means the loop condition is true, so it will print the message to the page and increment i by 1.
  2. Then, it will move back to the start of the loop and evaluate the condition. The condition is still true because i (now 2) is still less than 10, so it executes the code block again.
  3. This continues until i is 10, in which case the condition turns false and the translator stops looping.

Let’s try a more practical example.

Example:
<script>

  var i = 0;
  var user = ["John", "Jane", "Jack", "Jill"];

  while (user[i]) {

    document.write("User: ", user[i], "<br>");
    i++;
  }

</script>

For simplicity, we will pretend for the moment that the names in the user array comes from a database.

Our condition is slightly different than before. The translator will automatically stop looping when it reaches the end of the array, so we don’t have to specify explicitly how many times it should loop. All we have to do is increment the counter (i) that loops through the users.

We cover looping over arrays again in the Arrays tutorial.

The do while loop

The do while loop is sort of like an upside down while loop. The execution code is specified first, then the condition is checked.

To write a do while loop we use the keyword do , followed by a code block with the execution code. Then we specify the while condition.

Syntax:
do {

  // execution code

} while (condition);

Note that because the do while statement doesn’t end with a curly brace, it needs to be terminated with a semicolon.

Example:
<script>

  var i = 1;

  do  {
    document.write("Iteration no: ", i, "<br>");
    i++;

  } while (i <= 0);

</script>

In the example above we set the counter to 1. But, the condition will check if the counter is less than or equal to 0, so the condition is always false and the loop shouldn’t run.

When we refresh the page however, we see that the loop did run once. This is because the code block is executed before the translator could evaluate the condition and stop the loop.

A do while loop will always run at least once.

The for loop

A for loop is used when we know how many times the loop will repeat, like the number of hours in a day.

The syntax in a for loop is much more compact. It has the counter, the condition and the increment all in one place.

To write a for loop, we use the keyword for , followed by a condition block and then an execution block containing the code we want to have loop.

Inside the condition block we first set up our counter, followed by a semicolon terminator. Then we specify our condition, again followed by a semicolon terminator. Lastly, we increment the counter.

Syntax:
for (counter_setup; condition; counter_increment) {

  // execution code

}
Example:
<script>

  for (var i = 1; i <= 10; i++) {

    document.write("Iteration no: ", i, "<br>");
  }

</script>

The example above is exactly the same as our first while loop example. The only difference is the syntax. The counter setup and counter increment is done inside the condition block.

In a while loop we may not always need a counter. But, in a for loop we will always need a counter so the setup and increment is required.

Summary: Points to remember

  • We use loops like the while, do while and for loops to repeat specific sections of our code.
  • The while loop is used when we don’t know how many times a loop should repeat.
  • The do while loop is used when we don’t know how many times a loop should repeat, but it should be at least once.
  • The for loop is used when we know how many times a loop should repeat.
  • The for loop must specify its counter and the increment/decrement of that counter in the condition block of the statement.