Skip to main content

Command Palette

Search for a command to run...

A quick look at the forEach method in JavaScript

Updated
2 min read
D

Self taught developer, working with Nextjs, TypeScript, Graphql and React.

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!

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

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!']

Let's connect

Connect on Twitter - davidbell_space

More from this blog

David Bell

21 posts