JavaScript Array forEach() Method

The forEach() method calls a function for each element in an array. It does not return a new array and does not modify the original array. It’s commonly used for iteration and performing actions on each array element.

Syntax:

array.forEach(callback(element, index, arr), thisValue);

Parameters:

This method accepts five parameters as mentioned above and described below:

ParameterDescription
callbackThis parameter holds the function to be called for each element of the array.
elementThe parameter holds the value of the elements being processed currently.
indexThis parameter is optional, it holds the index of the current value element in the array starting from 0.
arrayThis parameter is optional, it holds the complete array on which forEach is called.
thisArgThis parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used as this for each invocation of the callback function, otherwise undefined is used as default.

Return value:

The return value of this method is always undefined. This method may or may not change the original array provided as it depends upon the functionality of the argument function. 

Example 1: In this example, the Array.forEach() method is used to copy every element from one array to another.

JavaScript
// JavaScript to illustrate forEach() method
function func() {

    // Original array
    const items = [12, 24, 36];
    const copy = [];
    items.forEach(function (item) {
        copy.push(item + item + 2);
    });
    console.log(copy);
}
func();

Output
[ 26, 50, 74 ]

Example 2: In this example, the method forEach() calculates the square of every element of the array.

JavaScript
// JavaScript to illustrate forEach() method
function func() {

    // Original array
    const items = [1, 29, 47];
    const copy = [];
    items.forEach(function (item) {
        copy.push(item * item);
    });
    console.log(copy);
}
func();

Output
[ 1, 841, 2209 ]

Supported Browsers:

We have a complete list of JavaScript Array methods, to check those please go through the Javascript Array Complete Reference article.