forEach

Run a function once for each array item.

Syntaxarr.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

Try it yourself
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.

Example · js
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.

Example · js
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.

Example · js
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

  • Be the first to comment on this lesson.
forEach — JavaScript | SoundsCode