Loops in JavaScript

testYourselfJavaScript JavaScript778 1 0

The loop in JavaScript and in any other programming language is a sequence of instructions repeated until a certain condition is met. The loop will stop only when the condition is no longer met.

Instead of calling each line of code separately, e.g. to display array elements:

var toys = ['car', 'ball', 'doll'];
console.log(toys[0]);
console.log(toys[1]);
console.log(toys[2]);

You can achieve the same effect using a loop:

var toys = ['car', 'ball', 'doll'];
for (var index = 0; index < toys.length; index++) {
    console.log(toys[index]);
} 

JavaScript provides several types of loops. Although all loops provide similar basic functionality, they are different in syntax and the moment when the condition that determines further calling of the loop is checked.

  • loop for
  • loop for ... of
  • loop for ... in
  • loop while
  • loop do ... while

For loop

The for loop repeats the specified instructions until the given condition is met, and its structure allows you to define the initialization, condition, and step performed after each iteration on one line of code.

The for loop in JavaScript has the following syntax:

for (initialization; condition; IncrementalExpression) {
     // code that will be executed in each iteration
 } 

The first parameter, initialization, is the expression that is executed before starting the loop. This expression usually initializes one or more variables that are loop counters.

The second parameter specifies the condition for starting the loop. Usually, this expression is used to check the status of a counter. If the condition is met, the loop will run again. If the condition is not met, the loop will end.

The last parameter specifies the expression that is executed after each loop execution. Often, this expression is used to modify the counter.

for (var i = 0; i < 10; i++) {
    console.log(i);
}

In the example above, the loop will execute 10 times and display numbers from 0 to 9.

Each parameter is optional and can be omitted. However, omitting the parameters, we must remember about semicolons.

The first parameter responsible for initializing the counter can be omitted if the counter is initialized before executing the loop.

var i = 0;
for (; i < 10; i++) {
    console.log(i);
}

When we omit the second parameter of the for loop that defines the condition, we must ensure that the loop terminates its execution, e.g. by using the break keyword. Otherwise, the loop will never end, which will cause the browser to freeze.

for (var i = 0;; i++) {
    if (i === 10) {
        break;
    }
    console.log(i);
}

When we omit the third parameter of the for loop, which is responsible for modifying the counter, we must ensure that the counter is modified inside the for loop. Otherwise, the loop will run the same code over and over again and will never end.

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

In addition, we are not limited to using only one expression for each parameter of the for loop. However, we must remember that the expressions should be separated by commas.

for (var i = 0, j = 5; i <= 5, j >= 0; i++, j--) {
    console.log(i, j);
}

the above code will return the following result:

0 5
1 4
2 3
3 2
4 1
5 0

JavaScript for loops can also be nested:

var products = [
    [ 'necklace', 'ring', 'earrings'],
    ['bag', 'belt', 'backpack']
];
for (var i = 0; i < products.length; i++) {
    for(var j = 0; j < products[i].length; j++) {
        console.log(products[i][j]);
    }
}

Loop for ... in

Another type of for loop in JavaScript is the for ... in loop. The for ... in loop lets you iterate through the object's properties.

The for ... in loop has the following syntax:

for (variable in obj) {
    // code to be executed
}

By using the for ... in loop, we declare a variable to which individual object properties will be assigned each time the loop is called. A variable can be declared using the keyword let, const or var. The loop is called until all object properties are processed.

var player = {nickname: 'draz', age: 25};
 for (var prop in player) {
     console.log(prop);
 }

The above code will return the following result:

nickname
age

In each iteration, one of the player object properties is assigned to a variable named prop and the loop is called until all object properties are processed.

The for ... in loop also works with arrays:

var arr = [5,10,15];
for (var i in arr) {
    console.log(i);
}

The above code will return all array indexes:

0
1
2

Loop for ... of

JavaScript provides another type of for loop - for ... of loop. The for ... of loop allows you to iterate through the values of iterable objects such as arrays, maps, strings, array-like objects (e.g., arguments, NodeList) and others.

The for ... of loop has the following syntax:

for (variable of iterable) {
    // code that will be executed
}

Using a for ... of loop, we declare a variable to which the values of each iterative object property will be assigned each time the loop is invoked. The loop is called until all iterative object values have been processed.

An example of using the for ... of loop to iterate across an array:

var cars = ['bmw', 'ford', 'audi'];
for (var i of cars) {
    console.log(i);
}

The above code will return all elements of the array:

bmw
ford
audi

An example of using a for ... of loop to iterate over a string:

var str = 'JS';
for (var i of str) {
    console.log(i);
}

The above code will return individual letters from the given string:

J
S

An example of using the for ... of loop to iterate over the arguments object:

function foo() {
    for (var arg of arguments) {
        console.log(arg);
    }
}
foo(1,2,3);

The above code will return the following result:

1
2
3

Loop for ... in vs for ... of

Both for ... in and for ... of loops allow to iterate. The main difference between them is in what they iterate through.

The for ... in loop iterates through the properties of the object, while the for ... of loop iterates through the values of the iterative object.

var arr = [5,10,15];
for (var prop in arr) {
    console.log(prop);
}

the above code will return the following result:

0
1
2

and:

var arr = [5,10,15];
for (var val of arr) {
     console.log(val);
}

will return the following result:

5
10
15

Loop while

The while loop starts by checking the condition. If the condition is true then the code belonging to the while loop is executed. Usually, the code inside the while loop contains instructions to update the variables processed in the next iteration. If the condition is not met, the code outside the while loop is executed.

while(condition) {
    // code that will be executed when the condition is met
}

The while loop starts by checking the condition. If the condition is met, the while loop statement will be executed and the condition will be checked again. When the condition is not met, the loop will end.

var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var index = 0;
while (index < days.length) {
    console.log(days[index]);
    index++;
}

In the above example, in each iteration of the while loop, we display individual elements of the days array, and also increment the index variable by 1 until the index is larger than the size of the array. The condition check is done before each loop iteration.'

Loop do ... while

The do ... while loop is similar to a while loop except that it checks the condition only after executing the statement.

do {
    // the code that will be executed
} while(condition);

The do ... while loop starts with the loop statement. The condition is not checked at the first time. Only after executing the instruction and updating the variable value, the condition is checked. If the condition is met, the next iteration of the loop will start. When the condition is not met, the loop terminates.

var days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
var index = 0;
do {
    console.log(days[index]);
    index++;
} while (index < days.length);

In the example above, in each iteration of the do ... while loop, we display individual elements of the days array, and we also increment the index variable by 1 until the index is larger than the size of the array. The condition is checked after each loop iteration.

The keyword break i continue

When using loops in JavaScript, we can use the break and the continue keyword.

The break keyword lets you stop looping.

In the following example, the break keyword was used to stop the do ... while loop when the sum of the elements from the array exceeds 10:

var sum = 0;
var i = 0;
var arr = [2,6,10,15];
do {
    sum += arr[i];
    if (sum > 10) {
        break;
    };
    i++;
} while (i < arr.length);
console.log(sum); // 18

The continue keyword lets you skip a specific iteration in a loop and jump to the next iteration.

In the following code, the keyword continue is used to display only odd numbers:

var i = 0;
do {
    i++;
    if (i % 2 == 0) {
        continue;
    }
    console.log(i);
} while (i < 5);

The above code will return the following result:

1
3
5

An infinite loop

One of the most common errors when implementing any type of loop is the risk that the loop will not terminate. This happens when, for some reason, the condition fails.

for (;;) {
}

Executing this code will cause the browser to freeze.

Summary

  • a loop in JavaScript is a sequence of instructions that is repeated until the specified condition is met.
  • JavaScript provides several types of loops
    • loop for
    • loop for ... of
    • loop for ... in
    • loop while
    • loop do ... while
  • the for loop structure allows you to define initialization, condition and modify the counter in one line of code
  • each of the for loop parameters is optional and can be omitted
  • we can use more than one expression for each parameter of the for loop
  • the for ... in loop allows you to iterate through the properties of the object
  • the for ... of loop allows you to iterate through the values of iterable objects (arrays, maps, strings, etc.)
  • while loop starts its execution by checking the condition
  • do ... while loop checks the condition only after executing the statement
  • the break keyword lets you stop the loop
  • the continue keyword lets you skip a specific iteration in the loop