JavaScript (ES2026) reference · Array Methods

JavaScript Array forEach() Method

Call a function once for each element. It returns undefined, so use map() when you need a new array.

JavaScript (ES2026) Since ES5

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array.forEach(callbackFn, thisArg)

Parameters

ParameterDescription
callbackFn Called for each element with (element, index, array).

Return value

undefined.

Examples

Run code for each elementTry it yourself
["a", "b", "c"].forEach((letter, i) => console.log(i, letter));

Output

0 a
1 b
2 c
Accumulate a valueTry it yourself
let total = 0;
[5, 10, 15].forEach((n) => { total += n; });
console.log(total);

Output

30
Need to stop early? Use for…ofTry it yourself
for (const n of [1, 2, 3]) {
  if (n === 2) break; // for…of can stop early; forEach can't
  console.log(n);
}

Output

1

Common mistakes

  • You can't break out of forEach(). Use for…of, some() or find() instead.
  • forEach() doesn't wait for async callbacks. Use for…of with await, or Promise.all(arr.map(...)).

Version history

VersionChange
JavaScript ES5Added

In other languages

Was this page helpful?