Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
["a", "b"].forEach((letter, i) => console.log(i, letter));

Try it

JS Visiting every element

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS No break, no await

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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

  • return only skips to the next element. Inside the callback, return ends that call, not the loop (like continue). break is a syntax error there.
  • To stop early, use a for...of loop, or some() / 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. forEach starts every async callback and returns immediately; the second example prints "forEach finished" before any "async done" line. Use for...of with await, or Promise.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() or filter() say so more clearly and avoid an outer mutable variable.
  • Works on array-likes with Array.prototype.forEach.call(nodeList, fn); NodeList and Map/Set have their own forEach() 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.