JavaScript Reference ยท Array
JavaScript Array forEach() method
Reference for JavaScript Array forEach(): run a function once per element, with arguments, why it cannot break or await, and when to use for...of instead.
The forEach() method calls your function once for each element of an array, in index order. It is meant for side effects such as logging, updating the page or filling another structure. It always returns undefined, so you cannot chain from it.
Unlike a for loop, forEach() cannot be stopped early with break, and it does not wait for async callbacks. Those two facts cause most of the bugs people have with it.
["a", "b"].forEach((letter, i) => console.log(i, letter));
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
forEach(callbackFn) forEach(callbackFn, thisArg)
| Name | Description |
|---|---|
callbackFn |
Called as callbackFn(element, index, array). Its return value is ignored. |
thisArg |
Optional. Value used as this inside callbackFn (ignored by arrow functions). |
Return value: undefined.
Exceptions: a TypeError if callbackFn is not a function. Any error thrown inside the callback propagates out of forEach() and stops the iteration.
Usage notes
returnonly skips to the next element. Inside the callback,returnends that call, not the loop (likecontinue).breakis a syntax error there.- To stop early, use a
for...ofloop, orsome()/every()/find(), which stop when they know the answer. Throwing an error also works but is a poor control-flow tool. - It does not await.
forEachstarts every async callback and returns immediately; the second example prints "forEach finished" before any "async done" line. Usefor...ofwithawait, orPromise.all(arr.map(...)). - Holes are skipped, and elements appended during iteration are not visited, since the length is read once at the start.
- Do not use it to build arrays. If you create a new array from the results,
map()orfilter()say so more clearly and avoid an outer mutable variable. - Works on array-likes with
Array.prototype.forEach.call(nodeList, fn);NodeListandMap/Sethave their ownforEach()too. - Performance is similar to a plain loop for most code; pick on readability and the need to break or await.
Browser support
forEach() is supported in every current browser and has been for a very long time.