DEV Community

loading...

A quick look at the forEach method in JavaScript

davidbell_space profile image David Bell Originally published at davidbell.space Updated on ・1 min read

The forEach array method basically does something for each item in an array. Sounds straight forward...

In the example below we have an array of goodBoys. forEach item in the array we console log the item adding a ! to the end.

const goodBoys = ["Spike", "Humphrey", "Snuffles"]

goodBoys.forEach(item => {
  console.log(item + "!")
})
// Spike!
// Humphrey!
// Snuffles!
Enter fullscreen mode Exit fullscreen mode

Adding a second parameter to the function like below to get the index of each item in the array.

const goodBoys = ["Spike", "Humphrey", "Snuffles"]

goodBoys.forEach((item, index) => {
  console.log(item, index)
})
// Spike 0
// Humphrey 1
// Snuffles 2
Enter fullscreen mode Exit fullscreen mode

Note that forEach does not manipulate an array. It simply allows you to do something with each item. In the example below I have created an empty array called newArray. Using forEach to loop through each item and push() to append each item + ! into newArray.

const goodBoys = ["Spike", "Humphrey", "Snuffles"]
const newArray = []

goodBoys.forEach(item => {
  newArray.push(item + "!")
})
console.log(newArray)
// ['Spike!', 'Humphrey!', 'Sniffles!']
Enter fullscreen mode Exit fullscreen mode

Let's connect

Connect on Twitter - davidbell_space

Discussion

pic
Editor guide