forEach() Method

To iterate through an array’s items, the forEach() method can be helpful.

In this article, I’ll show how to use the forEach() array method to iterate items of an array in JavaScript.

I. What can .forEach() method do?

array.forEach() method calls a function and iterates over the array items in ascending order without mutating the array.

The syntax of the forEach() method is:

array.forEach(function(currentValue, index, arr));
  • callback function to be run for each element of an array
  • The value of an array
  • The index of the current element
  • The array of the current elements (optional)

Example: We display each element of an array.

With for-loop

let names = ["Anna", "John", "Peter"];

// using for-loop
for(let i = 0; i < names.length; i++) {
    console.log(names[i]);
}

With forEach

let names = ["Anna", "John", "Peter"];

// using forEach
names.forEach(function(name) {
    console.log(name);
});

Output

Anna
John
Peter

II. forEach with Arrow Function

We can use the arrow function with the forEach() method.

let names = ["Anna", "John", "Peter"];

// using forEach
names.forEach(name => {
  console.log(name);
});

III. Update the Array Elements

We can use the forEach() method to update the array elements.

let names = ["Anna", "John", "Peter"];

// using forEach
names.forEach(function(item, index, arr) {
    arr[index] = 'Hello ' + item;
});

console.log(names); // ["Hello Anna", "Hello John", "Hello Peter"]