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
Syntax
array.forEach(callbackFn, thisArg)
Parameters
| Parameter | Description |
|---|---|
callbackFn |
Called for each element with (element, index, array). |
Return value
undefined.
Examples
["a", "b", "c"].forEach((letter, i) => console.log(i, letter));
Output
0 a 1 b 2 c
let total = 0;
[5, 10, 15].forEach((n) => { total += n; });
console.log(total);
Output
30
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
breakout offorEach(). Usefor…of,some()orfind()instead. forEach()doesn't wait forasynccallbacks. Usefor…ofwithawait, orPromise.all(arr.map(...)).
Version history
| Version | Change |
|---|---|
| JavaScript ES5 | Added |
Related
array.map()· Return a new array with the results of calling a function on every element. The original array is unchanged.array.entries()· Return an iterator of [index, element] pairs, handy for looping with both the index and the value.array.every()· Return true if every element passes a test function. Stops at the first failure; an empty array returns true.- JavaScript Arrays · tutorial
- JavaScript Array Methods · tutorial