forEach

forEach(x, callback)

Try it yourself:

See also:

Visit collection elements with forEach

forEach(x, callback) invokes a callback for each element in a collection. It is designed for actions performed per value, such as logging, updating an accumulator, or applying an external effect.

Choose the right iterator

For a transformed collection, prefer map; for retained elements, use filter. ForEach does not normally create a useful replacement array, so it is best when the callback’s side effect is deliberate. count and size help establish how much data will be visited.

Cautions

Callbacks should handle element types consistently and avoid changing the collection while it is being traversed unless the behavior is known. For numeric summaries, direct functions such as sum or mean are clearer and less error-prone.

All functions