# forEach() Function & Examples

Use the forEach() matrix function in Calcul.io. Review its syntax, edit working examples, understand the result, and explore related math functions.

## forEach

#### forEach(x, callback)

Try it yourself:

```calculio
numberOfPets = {}
addPet(n) = numberOfPets[n] = (numberOfPets[n] ? numberOfPets[n]:0 ) + 1;
forEach(["Dog","Cat","Cat"], addPet)
numberOfPets
```

[map](https://calcul.io/function/map/index.md)

[sort](https://calcul.io/function/sort/index.md)

[filter](https://calcul.io/function/filter/index.md)

---

## 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](https://calcul.io/function/map/index.md); for retained elements, use [filter](https://calcul.io/function/filter/index.md). ForEach does not normally create a useful replacement array, so it is best when the callback’s side effect is deliberate. [count](https://calcul.io/function/count/index.md) and [size](https://calcul.io/function/size/index.md) 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](https://calcul.io/function/sum/index.md) or [mean](https://calcul.io/function/mean/index.md) are clearer and less error-prone.

[All functions](https://calcul.io/functions/index.md)
