Open In App

JavaScript Array forEach() Method

The arr.forEach() method calls the provided function once for each element of the array. The provided function may perform any kind of operation on the elements of the given array. 

Syntax:

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

Parameters:

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



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 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 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.


Article Tags :