A repetition is a block of code that is executed multiple times in a loop. Each repetition is called an iteration. The number of iterations can be controlled by a control variable or by a condition. A repetition can be interrupted using break and we can create shortcuts using continue keyword.

 

In JavaScript we have several kind of repetition statements:

  • for – loops through a block of code a number of times
  • for/in – loops through the properties of an object
  • while – loops through a block of code while a specified condition is true
  • do/while – also loops through a block of code while a specified condition is true

 

For

var text = ""

for (i = 0; i < 5; i++) {
    text = "i = " + i;
    console.log(text)
}

In this example i=0 define a new variable i that is the control variable.

For statement has 3 parts:

  1.  declaration of control variable
  2.  termination condition
  3.  increment

 

For in

var person = {first_name:"John", last_name:"Doe", age:25};

var text = "";
var x;
for (x in person) {
    console.log(x);
    text += person[x]+" ";
}

console.log(text);

In this example we use in operator to iterate over an iterable object that is person. The text variable starts empty and accumulate data from person object attributes.  Notice x is not a number but instead a string that have values: first_name, last_name or age. To get the value we use person[x]

 

While

var i = 2;

while (i < 10) {
    console.log("i = " + i);
    i++;
}

In this example we start with i=2 and we continue until i=9 then exit. Notice we use i++ to increment the control variable i. If we do not increment i the loop will never end.

 

Do while

var i = 2;

do {
    console.log("i = " + i);
    i++;
} while (i < 10);

The only difference from previous example is that condition is check at the end of the loop not at the beginning. This difference allows execution of the block at least once even if the condition will not allow a second iteration.