How to Use forEach in JavaScript
Running a function for every item in an array with forEach.
You will often need to do something with every item in an array, like logging
it, saving it or adding it to the page. You could write a for loop with a
counter, but forEach does the same thing with less code to keep track of.
The forEach() method calls your function once for every item in an array.
How forEach Works
forEach takes a callback and runs it for each item, in order:
arr.forEach((element, index, array) => {// do something with element})
The callback gets the current element, its index and the original array.
Here's the same loop written both ways:
const fruits = ["apple", "banana", "cherry"]for (let i = 0; i < fruits.length; i++) {console.log(fruits[i])}fruits.forEach((fruit) => {console.log(fruit)})// console: apple// console: banana// console: cherry
With forEach there's no counter to set up and no fruits[i] to get wrong.
A Practical Example
forEach is a good fit for side effects, where you're changing something
outside of the loop. Here we add a list item to the page for each fruit:
const list = document.querySelector("ul")fruits.forEach((fruit, index) => {const item = document.createElement("li")item.textContent = `${index + 1}. ${fruit}`list.appendChild(item)})
It works on NodeLists too, so you can loop over the result of
querySelectorAll in modern browsers:
document.querySelectorAll("button").forEach((button) => {button.addEventListener("click", () => console.log("clicked"))})
forEach Returns undefined
forEach doesn't return anything. If you're trying to build a new array from
the old one, use map instead:
const upper = fruits.forEach((fruit) => fruit.toUpperCase())console.log(upper) // undefinedconst upperFruits = fruits.map((fruit) => fruit.toUpperCase())console.log(upperFruits) // ["APPLE", "BANANA", "CHERRY"]
If you're new to map, I wrote about it in
How to Use the map Method in JavaScript.
You Can't Break Out of forEach
A for loop lets you break once you've found what you need. forEach always
runs for every item, and return only skips to the next one:
fruits.forEach((fruit) => {if (fruit === "banana") return // skips banana, keeps goingconsole.log(fruit)})// console: apple// console: cherry
Note: If you need to stop early, use a regular for loop or for...of.
For most "do this for every item" jobs though, forEach is the easiest loop to
read.
Have some feedback on this post? .