JavaScript/Loops

JavaScript supports the repetitive execution of code blocks via the keywords  and. Similar behavior is offered by the  method of data type   (and similar data types).

for {}
The syntax of the  statement is:. It is executed based on the following rules:


 * 1) The   is executed - exactly once for the complete   statement. Usually, it declares and initiates one or more variables - often numbers with integer values. Sometimes the declaration of the variables is made above the   statement.
 * 2) The   is evaluated. If it returns , step 3 follows. If it returns , the   statement terminates.
 * 3) The code block is executed.
 * 4) The   is executed. Usually, it increments or decrements a variable that is part of the.
 * 5) The loop repeats at step 2.

An example: Show the series of even numbers multiplied by itself (power 2); show the sum over the numbers from 0 to 10.

Optional syntax parts
The, the  , and the   are optional. If you omit one or more of them, your script shall perform other useful statements to control the loop. Some examples:

Nesting
loops can be nested. You can use a second (or 'inner') loop within the block of the first (or 'outer') loop.

This nesting of loops is also possible in all the below constructs.

continue / break
Sometimes only parts or the block shall run. This can be realized by one or more  statements. If it's appropriate, such conditional statements can be shortened by the keyword. If  is reached, the rest of the block is skipped, and the above step 4   is executed.

This example is very simple. It skips the lower part of the block for the case where  equals to 5. Of course, it can be expressed differently. A more realistic example would be a loop over the result of a database search which skips parts of a complex handling of rows with a specific status.

The  keyword is similar but more rigid than the   keyword. It skips not only the rest of the block but also terminates the complete loop.

A realistic scenario is a loop over the result of a database search where the connection to the database is broken in the middle of the loop.

You can use  and   in all forms of the here-discussed variants of loops.

do {} while
The syntax of the statement is:. It is executed based on the following rules:
 * 1) The block is executed. Because this is the very first step, the block is executed at least 1 time. This is helpful if you want to be sure that something happens under all circumstances.
 * 2) The   is evaluated. If it returns , step 1 is invoked again. If it returns , the loop terminates. Please notice that there is no specific part where you can manipulate a variable that is checked in the condition. This must be done somewhere in the block among the other statements.

while {}
The syntax of  is very similar to the previous. The only difference is that the condition is checked before and not after the block.

for (x in Object) {}
This language construct is intended to iterate over the properties of an object. Its syntax is:. The variable receives the key of all properties - one after the next - of the object. For each of them, the block is executed once.

Arrays are specialized objects. Hence it is possible to use the  on arrays. The keys for arrays are integers starting with 0 - and that is precisely what is extracted from the array.

Arrays also accept non-numeric keys, e.g.,. The  loop handles such non-numeric keys - in opposite to the below   loop, and in opposite to the traditional   loop at the top of this page.

See also: MDN: for..in

for (x of Array) {}
This language construct is intended to iterate over an array. Its syntax is:. The variable receives all values - one after the next - of the array. For each of them, the block is executed once.

This definition sounds similar to the above definition of the. But there are significant differences:
 * It returns the values, not the keys resp. index of the array.
 * It works only on all iterable objects (Array, Map, Set, ...). The data type 'object' is not iterable.
 * It works only on such keys which are numeric. Non-numerical keys resp. index are silently ignored.

See also: MDN: for..of

for..in vs. for..of
The differences between the two language constructs are summarized in an example.

Object.entries method
If you are looking for a loop that processes both keys and values of an object, there is a more straightforward method than the above-shown combination of the  with. The data type Object offers the  method that returns an array. Each element of this array contains an array with two values: the property key and the property value. In other words: the return value of the  method is a two-dimensional array. And - as usual with arrays - you should use it in combination with.

Hint: The  as well as the following   methods are no 'core' language elements like keywords or the   or   language constructs. They are methods of the Object respectively Array data type.

Array.forEach method
The data type Array offers the method. It loops over the elements of the array, returning one element after the next. The interesting point is that it takes a function as its argument. This makes the difference to the divers  and   loops. Such functions are often called callback function.

The method invocation is very easy:. The - possibly - confusing part is that function calls can be abbreviated in various ways.

The first example shows the function call explicitly. It defines the function myFunction which also takes a single argument. When myFunction is called by forEach, the next array element is inserted as the argument to myFunction.

The following examples show some abbreviations of the function invocation syntax.

It depends on your preference, which syntax you use.

In many cases, the called function performs side effects like logging. To calculate values over all array elements, it is necessary to use the technique of closures. In the following example, the variable  is not defined in the outer context, not in the anonymous function.

All in all, the following rules apply to the  method:
 * The method can be used for iterable objects like Array, Map, Set. The data type Object is not iterable.
 * The method only iterates over such elements which have a numerical key - what is the usual case for arrays.

See also:
 * MDN: forEach
 * MDN: Iterative methods

Exercises

 * ... are available on another page (click here).