Learning Javascript forEach Loop


JavaScript has multiple different types of loops. Each loop has its own use case and is used in different situations. One such loop (which is actually a method) is the forEach loop.

In this article, we are going to look at the forEach loop in detail and learn how to use it in our code.


What is forEach Loop?

forEach is an array method that is used to iterate (loop) over an array.

It executes a function on each element of the array.

forEach method is an easy and efficient way to iterate over an array and perform a specific operation on each element.


Syntax

The syntax of forEach loop is as follows:

array.forEach(function(currentValue, index, array) {
    // code to be executed
});

The forEach() method takes in a callback function as its argument (which is executed for each element). This callback function has three parameters:


Examples

Let's look at some examples to understand how forEach loop works.

Example 1

Here is an example of an array of numbers that squares each number in the array and prints the result using forEach loop.

Example

const numbers = [1, 2, 3, 4, 5];

// using forEach loop
numbers.forEach(function(number) {
    console.log(number * number);
});

Example 2 - Using Index

The following example shows how to use the index parameter of forEach loop.

Example

const numbers = [5, 8, 12, 32, 14];

// using forEach loop
numbers.forEach(function(number, index) {
    console.log(index + " : " + number);
});

Example 3 - Using forEach with Strings

You can also use forEach loop to iterate over a string and perform a specific operation on each character.

First, you will have to convert the string into an array by splitting it into characters.

Example

const str = "Hello";

// using forEach loop
str.split("").forEach(function(char) {
    console.log(char);
});

Break and Continue

It is not possible to use the break or continue statements within a forEach() loop. However, you can use the return statement to exit the loop early.

For example, you can use the return statement to exit the loop when a certain condition is met:

Example

let numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(currentValue) {
    if (currentValue > 3) {
        return;
    }
    console.log(currentValue);
});
// Output: 1 2 3

Additional Features

The forEach() method also has the option to provide this value as an additional argument.

It is used to set the value of this within the callback function. You can pass the reference to an object as the this value.

For example:

Example

let numbers = [1, 2, 3, 4, 5];
let sum = 0;
let object = {
    sum: 0
};

numbers.forEach(function(currentValue, index, array) {
    this.sum += currentValue;
}, object);

console.log(object.sum); // Output: 15
console.log("Outer sum = " + sum); // Output: 0

In the above example, the this value is set to the object variable. So, the sum property of the object is updated.


forEach vs for Loop

The forEach() method is a convenient way to iterate over an array. However, it is not always the best choice.

For example, if you need to break out of the loop, you can't use the forEach() method. In such cases, you should use the for loop.

Here are some other differences between the forEach() method and the for loop:

forEach() for Loop
Can't break out of the loop Can break out of the loop
Can't skip an iteration Can skip an iteration
Can't use return statement Can use the return statement
It takes a callback function as an argument It has a block of code to execute as its body

Alternative Methods

There are a few other methods that can be used to iterate over an array in JavaScript, such as the map() and reduce() methods. These methods also take a callback function as their argument and can be used to perform operations on each element of an array.

Here is an example of using the map() method to achieve the same result as the forEach() loop in the first example:

Example

let numbers = [1, 2, 3, 4, 5];

let result = numbers.map(function(currentValue) {
    return currentValue;
});

console.log(result);

// Output: [1, 2, 3, 4, 5]

It is important to choose the appropriate method based on your specific needs. The forEach() method is a good choice when you simply want to iterate over an array and perform an operation on each element, whereas the map() method is useful when you want to transform each element of an array and return a new array.


Quiz - Javascript forEach tutorial quiz

What is the syntax for the forEach() method in JavaScript?
Can the break or continue statements be used within a forEach() loop?
What is the this value in the forEach() method used for?
Can the forEach() method be used to transform the elements of an array and return a new array?
What is the output of the following code?
let numbers = [1, 2, 3, 4, 5];
let result = [];

numbers.forEach(function(currentValue, index, array) {
    result.push(currentValue * 2);
});

console.log(result);

Conclusion

In this tutorial, you learned about the forEach() method in JavaScript. You also learned about the syntax and usage of the method.

The forEach() method is useful and efficient when you want to iterate over an array and perform an operation on each element.

Happy coding!🙂