DEV Community

Cover image for Array.forEach() - for looping through items in an array
Dillion Megida
Dillion Megida

Posted on • Updated on

Array.forEach() - for looping through items in an array

This article is the fourth of the Array Method series. Here, I'll explain the forEach array method.

Here's the video version: Array.forEach() YouTube

What is the forEach method?

The forEach method is very similar to the map method. The difference is that the map method loops through each item and returns a new array, while the forEach method only loops and returns nothing.

The forEach method of arrays is a higher-order function that loops through each item in the array and performs some operations on the items.

As a higher-order function, it takes a function as an argument. During the loop, this function receives an item (and its index position in the array), and you can do whatever you want with that item.

Syntax of the forEach method

someArray.forEach(function(item, index, array) {
  // something with item and/or index
})
Enter fullscreen mode Exit fullscreen mode

The item argument is the item being looped on.

The index argument is the position in the array. For example, the first item has an index of 0, and the second, 1.

The array argument is the array itself.

Without the forEach method

The forEach method is a declarative abstracted method that literally "does something for each item". Here's an example showing how you can loop through an array without this method:

const array = [...]

for(let i = 0, i < array.length, i++) {
  const item = array[i]
  // do something with item
}
Enter fullscreen mode Exit fullscreen mode

This loop approach is similar to what the forEach method does behind the scenes.

With the forEach method

For example, you want to concatenate strings in an array to one string. Here's how:

const array = ["apple", "banana", "cashew", "pawpaw"]

let string = "I bought "

array.forEach(function(item, index) {
  if (index === 0) {
    string += item
  } else if (index === array.length - 1) {
    string += ` and ${item}`
  } else {
    string += `, ${item}`
  }
})

console.log(string)
// I bought apple, banana, cashew and pawpaw
Enter fullscreen mode Exit fullscreen mode

Oldest comments (1)

Collapse
 
frankwisniewski profile image
Frank Wisniewski

Basically your example is OK.

Exactly this project can be represented in one line...

console.log(
    `I bought ${new Intl.ListFormat("en-GB").format
    (["apple", "banana", "cashew", "pawpaw"])}.`
    )
// I bought apple, banana, cashew and pawpaw.
Enter fullscreen mode Exit fullscreen mode