Menu Close

Articles

JavaScript: repetition

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 loop

Execute a block of code for a specific number of times. This loop is controlled by an integer variable that is local to the block. In next example “i” play the role of control variable:

For statement has 3 parts:

  1.  initialization of control variable
  2.  termination condition
  3.  increment expression

Control Variable:

  • control variable can be declared local using “let”,
  • control variable can be declared using “var”,
  • control variable is available in parent scope if is declared with “var”.

For…in loop

This statement uses a visitor: x that enumerate members of an object. In next example we scan properties of a person object using “for in” loop and display each value.

Note: In this example we use in operator to iterate over an object person. The “text” variable starts empty and accumulate data from person 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].

For…of loop

To iterate over values of an array you can use “for…of” loop. This is a bit different than “for…in” and you have to understand both before use them with array object. Notice an array in JavaScript is also an object so you can use both these statements with different results:

Example:

Notice: The difference is:

  • using “in” will get the “key” of the array;
  • using “of” will get the value of elements from the array.

While loop

It is a repetitive statement that execute as long as one condition is true. When the condition becomes false the statement will stop and control is given to next statement. If the condition is false in the first place, the loop will never execute.

Note: 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

This is a repetitive statement that execute at least once. It is controlled by a condition that evaluate only after first execution. When the condition becomes false, the repetition stop and control is given to next statement.

Read next: Math