Understand the forEach() method in JavaScript5 min read

The forEach method is one of the most searched JavaScript tutorials on the internet. The Array.prototype.forEach() method was introduced in ES6 for looping through arrays. Basically, this method executes a function on each element in an array.

The forEach method is simple, this is one of the prototypes of Array structure in JavaScript, hence it is mainly applied and gets invoked by an array, but also it can be used in Map, and Set as well.

If you also want to learn about map, filter, and reduce methods and want to compare those with the forEach method, check out this article I wrote recently.

forEach’s Syntax

First off, let’s take a look at this method’s syntax:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

As we can see, the forEach method accepts a callback function, this callback function is called on each of array’s elements. The callback function takes 3 parameters, but 2 of them are optional index and array, which are indicated by the [ ]. Let’s take a closer look on each of the element in this forEach method:

  • callback
    • currentValue: the current element in the array being processed, the currentValue will be sequentially picked up from the beginning of the array to the end, from the first array element to the last one.
    • index (optional) : the index of currentValue
    • array (optional): the array which the forEach method was called.
  • thisArg (optional): uses this value when executing the callback.

After finishing execution, this forEach method returns nothing, this is the reason why you usually notice undefined value after using this method.

Examples

Let’s move on some concrete examples to understand how theforEach method works.

Print the array’s elements

Most of the time, we just have to take care of the first parameter of the callback function inside the forEach method:

var names = ["Ethan", "Oliver", "Jacob", "Michael"];

function callback(currentValue, index, array) {
    console.log("Hello " + currentValue);
}

names.forEach(callback);

/*
Hello Ethan
Hello Oliver
Hello Jacob
Hello Michael
*/

Let’s break down what’s happening here:

  • On the very first line, we create an array names and inside this array are some common names in English.
  • Next, we define a callback function named callback which will be invoked on every element of the array which the forEach method is called upon, this function takes 3 parameters as in the syntax declaration, but we only use the first one currentValue. Inside this function, it takes the first argument and logs greeting message to the console.
  • Right below, we call the forEach function on our names array and pass in the callback function. This callback function gets called on every element on the array.

For more details, our array has 4 elements and this callback function will be called 4 times. The first element will be passed to the callback function will be “Ethan” as the currentValue, that why we see Hello Ethan in the first pass, the same thing happens to the rest.

How the callback function gets called is done internally, we just need to know this callback function is called in each of the array elements. But if you’re interested in how the callback function is called under the hood, check out this ECMAScript documentation.

We can rewrite this example above with a more concise version with the help of arrow function syntax:

names.forEach((currentValue) => console.log("Hello " + currentValue));

We can use all of those 3 parameters we provide in the callback function if we wanted to:

var arr = ["First", "Second", "Third"];

arr.forEach((currentValue, index, array) => {
    console.log("arr" + "[" + index + "]" + " is " + currentValue + ", " + "arr: " + array);
});
/*
arr[0] is First, arr: First,Second,Third
arr[1] is Second, arr: First,Second,Third
arr[2] is Third, arr: First,Second,Third
*/

Modify the existing array with the forEach()

The forEach method also is applied in many other conditions, one of those is modyfing the existing array:

var arr = [2, 3, 4, 5, 6];

arr.forEach(currentValue => {
    if(currentValue == 4){
        arr.splice(arr.indexOf(4), 1);
    } 
})
console.log(arr); // [2, 3, 5, 6]

We initially have an array named arr witt some numbers. Then use the forEach method to iterate through all elements of the array in order. Inside this method we have an anonymous callback function, this function will remove the element with the value equals 4 in the array arr.

Here we use the splice method to remove an element at the index position of the value 4. You can learn more about the splice method in this article.

Now we want to add 10 to each element of the array, we simply do as follow with the forEach method:

arr.forEach((currentValue, index) => {
    arr[index] = currentValue + 10;
});

console.log(arr); // [12, 13, 14, 15, 16]

Convert for loop to forEach

With the typical for loop, we usually do this same procedure to get the sum of an array:

var arr = [10, 20, 30, 40];
var sum = 0;
for(let i = 0; i < arr.length; i++){
    sum += arr[i];
}
console.log(sum); // 100

We can use the forEach method for this purpose:

arr.forEach(currentValue => sum += currentValue);
console.log(sum); // 100

forEach method skips empty elements

The forEach method will skip empty elements of the array, for example:

var arr = [2, 3, , 5, 6];
arr.forEach((currentValue, index) =>{
    console.log(currentValue + " at the index: " + index);
})

Output:

2 at the index: 0
3 at the index: 1
5 at the index: 3
6 at the index: 4

As you can see, the element at the index 2 is skipped because there is no value there.

forEach() and DOM manipulation

The forEach method is used frequently to manipulate the DOM elements, for example, we want to adjust the color and font of some HTML elements:

<div class="test">Hello</div>
<div class="test">Nice</div>
<div class="test">To</div>
<div class="test">Meet</div>
<div class="test">You!</div>  
<script>
       const arr = Array.from(document.getElementsByClassName("test"));
       arr.forEach(element => {
           element.style.fontFamily = 'Comic Sans MS';
           element.style.color = 'red';
       })
</script>

In this example, we wrap all the div with the class name equal “test” and store to the arr variable, this method getElementsByClassName returns a NodeList, this is the reason why we need to convert it into an array and then applying the forEach method. By using forEach, we provide a single parameter element which lets us iterate through all elements and change the font family and text color for each.

forEach() vs map()

The forEach and map methods have some similarities, there is an obvious distinction that the forEach returns undefined and the map method returns a new array:

var arr = [1, 2, 3, 4];

var forEachReturns = arr.forEach(e => console.log(e));
console.log(forEachReturns); // undefined;
var mapReturns = arr.map(e => e);
console.log(mapReturns); // [1, 2, 3, 4];

Previous Article
Next Article

Sign up for newsletter

* indicates required

Categories

Archives