07 - Loops in Javascript

In general, what is a loop? A loop is generally a closed path that has no visible start or end. Remember rubber bands? They do not have a start or an end. One can simply trace along its length in circles and would not reach an end.

Concept of loops

When it comes to loops in javascript, we can use them to repeat certain statements a certain number of times. The block of statements that is to be executed repeatedly is called the body of the loop. It may be a single statement or multiple statements.

So, what determines how many times the body of the loop should be executed?

The loops would have a condition check. If the condition evaluates to true, then the body of the loop is executed. After that, the condition is evaluated again. If it evaluates to true, then the body is executed again. If not, the statement that comes after the body of the loop is executed and so on. Each loop statement is suited to certain conditions and should be used wisely.

Iteration of the loop

A single time of execution of the body of the loop is called iteration. After each iteration the condition for the loop is checked.

Break statement

Remember the break statement that we used in switch case? It made the flow break to the statement following the switch case. In loops, when a break statement is encountered in the body of the loop, then the rest of the body of the loop is skipped and the control of execution exits the loop. The statement following the body of the loop is executed.

Continue statement

This is also a special statement like the break statement. Whenever the continue statement is encountered in the body of the loop, the rest of the body of the loop is skipped and the control proceeds to the next iteration.

The for loop

This loop statement is used in cases when the body of the loop has to be executed on a counter like basis. There are three parts of this loop, the initialization part, the conditional expression, the increment or the decrement part. This statement is followed by the body of the loop. Each part in the loop statement is separated by semicolons. Since this loop operates on count basis, the variable involved in it is called the counter variable. One can use an already declared variable or declare a variable specifically for the loop. When specifically created for the loop, the variable ceases to exist beyond its body.

The condition part may or may not be used. If used, the condition will be evaluated before going in for iteration. If it is not specified, then it is considered to always evaluate to true.

for(initialization;condition;iteration)
{
  //statements constituting the body of the loop
}

Shall we display the first 3 natural numbers in message boxes individually? Though we would find any practical use for displaying them as message boxes, this would certainly help us understand the nuances of how the loop works.

We will create a variable named n. The values to be printed are 1, 2 and 3. We will initially assign n as 1. After each iteration of the loop, the value of n should be incremented by 1. Now, we know that there is infinite number of natural numbers and we should have a condition in place to exit the loop after displaying 3. This is where we will put in the condition. It should either by 3 or less than 3. We can even say less than 4. Shall we write out the loop?

<!Doctype HTML>
<html>
  <head>
   <script type="text/javascript">
     for(var n = 1;n<4;n++)
     {
      document.write(n + ' ');
     }
   </script>
  </head>
  <body>
  </body>
</html>

The + “ “ adds a space after n is printed out to the screen. Remember, HTML is all text. So, we will join together bits of string using the + symbol. It is called concatenation. We will learn in detail about strings and their manipulation shortly.

Now, we will see an example for using the break statement and the continue statement. The break statement causes the flow to exit the loop and terminate the current iteration and skip to the statement after the body of the loop.

The continue statement will skip the body of the loop that follows it and move onto the next iteration. Here we do not have a condition in place to exit the loop. We leave it to the if condition and the break statement to do it.

Here a variable n is declared and is initialized to 0. Every time, n is checked for equality to 2. If so, the rest of the iteration is skipped. After writing the value of n, the value of n is checked for equality to 5. If it equals 5 then the loop will be terminated and the control will start executing the statement present after the loop.

With this example we can print from 0 to 5 with the exception of 2.

<!DOCTYPE html>
<html>
 <head>
  <script type = "text/javascript">
    for(var n = 0;;n++)
    {
      if(n==2)
       continue;
       document.write(n + " ");        
      if(n==5)
       break;
   }        
  </script>
 </head>
 <body>
 </body>
</html>

There is a variant of for loop called for each..in which can be used to iterate over the property values of objects but they are being deprecated, meaning they will not be available for use in future versions from Javascript 1.6.

For..in loop

The for..in loop can iterate over the properties of an object.

for(var property in objectname)
{
  //Statements that make the body of //the loop.
}

Let us see an example of an object named car that is assigned with properties. We will use the for in loop to iterate the properties along with their name and display them in the document.

<!DOCTYPE html>
<html>
  <head>
   <script type = "text/javascript">
     var car = {name:'Ritz', make:'Maruti'};
     for(var carProperty in car)
     {
       document.write(carProperty + " : " + car[carProperty] + "<br/>");
     }
   </script>
  </head>
  <body>
  </body>
</html>

While loop

The next kind of looping statement is the ‘while loop’. This loop is used when a statement or a block of statements should be executed based on a condition. The loop has a condition which is evaluated before executing an iteration. When the condition evaluates to false, the body of the loop is skipped and the statement following the body of the loop is executed.

while(condition)
{
  //statements that comprise the body of the loop
}

Let us take the previous example of printing the first 5 natural numbers. We can use this loop but we will have to take care of the logic internally. We declare and initialise a variable. We can specify the condition inside the while condition. Then, we can take care of the increment within the body of the loop.

<!DOCTYPE html>
<html>
  <head>
   <script type = "text/javascript">
     var n = 1;
     while(n<5)
     {
       document.write(n + " ");
       n++;
     }        
   </script>
  </head>
  <body>
  </body>
</html>

The do..while loop

The do..while loop is similar to the while loop with a small change. The condition comes after the body of the loop. The change is that, with a while loop, the body of the loop gets executed only if the condition that encloses it evaluates to true. With the do..while loop, the body of the loop gets executed at least once. We can say that for the first iteration, the condition is not evaluated. From the second iteration onwards, the body of the loop will be executed only if the condition evaluates to true. So, if you would like the body of the loop to be executed at least once irrespective of the condition then you should use a do..while loop.

do
{
  //Statements that make the //body of the loop.
}while(condition);

Let us use the same example above. Here the difference would be that the first number would be printed irrespective of what the condition says. One can notice by initialising the variable n to 6.

<!DOCTYPE html>
<html>
  <head>
   <script type = "text/javascript">
    var n = 6;
    do
    {
     document.write(n + " ");
     n++;
     }while(n<5);        
   </script>
  </head>
  <body>
  </body>
</html>

 

Like us on Facebook