JavaScript forEach: run callback on array items

JavaScript array forEach (Array.prototype.forEach) runs a callback once per element in an array, in index order. Use a JavaScript forEach loop for side effects—logging, DOM updates, or updating an outer variable—when you don’t need break or await. Because it returns undefined, it’s the wrong tool for transformations (map) or searches that can stop early (find, some). For control flow, prefer a for...of loop.

JavaScript forEach Example For Array Iteration

Output:

Output will appear here...

Output:

0: red
1: green
2: blue

How This Example Works

  1. colors holds three strings in an array.
  2. forEach calls the arrow function once per element, passing the current element and its zero-based index as arguments.
  3. The callback logs each color paired with its position. forEach processes elements in ascending index order and skips empty slots in sparse arrays.

Common forEach Pitfalls

Using forEach with async/await:

Wrong:

const urls = ["https://example.com/a", "https://example.com/b"];

urls.forEach(async (url) => {
  await fetch(url);
});
console.log("done"); // runs immediately

Right:

for (const url of urls) {
  await fetch(url);
}

forEach doesn’t await promises returned by the callback. Use for...of for sequential await, or await Promise.all(urls.map((url) => fetch(url))) for parallel work.

Trying to break out of forEach:

Wrong:

const items = ["a", "b", "c"];
const target = "b";

items.forEach((item) => {
  if (item === target) break; // SyntaxError
});

Right:

const found = items.find((item) => item === target);

forEach can’t exit early. Use find/some for short-circuit searches, or for...of when you need break.

forEach vs map vs for…of

FeatureforEachmapfor...of
ReturnsundefinedNew array— (loop)
Early exitNoNobreak / return
await friendlyNoWith Promise.allYes
Best forSide effectsTransformationsControl flow

Use forEach for side effects when early exit and await are not needed. Use map when the result is a transformed array. Use for...of when you need break, continue, or sequential await.

FAQ

Can you break out of JavaScript forEach early?

No. forEach runs the callback for every element. Throwing an exception stops iteration, but that is an anti-pattern. Use for...of with break, or find/some/every for short-circuit searches.

Does forEach mutate the original array?

forEach itself does not modify the array. The callback can mutate object elements in place because it receives references, not copies. Primitive values like numbers and strings are passed by value and cannot be changed through the callback parameter.

What is the difference between forEach and map?

forEach returns undefined and is designed for side effects. map returns a new array built from callback return values. If the goal is to transform data, use map; if the goal is to perform actions like logging or DOM updates, use forEach.