forEach
Run a function once for each array item.
Syntax
arr.forEach((item, index) => { ... })forEach() calls a function once for every item in an array. It is a clean replacement for a basic for loop when you just want to act on each item.
Callback arguments
The callback receives the item, its index, and the whole array.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Render each product in a results array as a DOM card element using a forEach loop.
- Send an analytics event for each item in a checkout order without needing the resulting array.
- Log each validation error from an errors array to the console for debugging.
More examples
Log each element
Calls the callback once per element, printing each fruit name to the console.
const fruits = ["apple", "banana", "cherry"];
fruits.forEach(fruit => console.log(fruit));forEach with index
Uses the optional index parameter to number each task in the output.
const tasks = ["Design", "Develop", "Test"];
tasks.forEach((task, i) => {
console.log(`${i + 1}. ${task}`);
});Build DOM nodes with forEach
Creates a list item for each navigation label and appends it to an unordered list element.
const items = ["Home", "About", "Contact"];
const ul = document.createElement("ul");
items.forEach(text => {
const li = document.createElement("li");
li.textContent = text;
ul.appendChild(li);
});
document.body.appendChild(ul);
Discussion