forEach method to iterate over an array in JavaScript

The next method we will learn is called forEach. It works just like the map method, only it doesn't return the modified array, but simply calls the callback function for each element of the array.

Let's look at an example. Let's have an array like this:

let arr = ['a', 'b', 'c', 'd', 'e'];

Let's output a column of array elements:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.forEach(function(elem) { document.write(elem + '<br>'); });

And now, in addition to the array elements, we will also display their indices. To do this, let's make a second variable index, which will contain the indices of our elements:

let arr = ['a', 'b', 'c', 'd', 'e']; arr.forEach(function(elem, index) { document.write(index + '. ' + elem + '<br>'); });

forEach application

At first glance, the forEach method doesn't seem very useful, as it doesn't return anything. In fact, you can simply make a variable located outside the callback:

let result; // the external variable arr.forEach(function(elem) { // the variable result is available here });

Using this technique, we'll find, for example, the sum of the array elements:

let arr = [1, 2, 3, 4, 5]; let sum = 0; arr.forEach(function(elem) { sum += elem; }); console.log(sum);

Given an array of numbers. Use the forEach method to find the sum of the squares of this array elements.

Comment

The forEach method appeared in JavaScript before the new for-of loop. Basically, the two iteration methods are similar, but the for-of loop has a simpler syntax, so it's likely that you'll use it more often.

enru