iteration
Array.prototype.forEach
Executes a provided callback once for each array element, in ascending order. Reach for it when you need side effects (logging, DOM updates, pushing to another store) and do not need a return value.
arr.forEach(callbackFn[, thisArg]) Parameters
| Parameter | Purpose |
|---|---|
| callbackFn(element, index, array) | Function invoked for each element |
| thisArg | Value used as `this` inside callbackFn |
Examples
['a','b','c'].forEach((v, i) => console.log(i, v)); Logs: 0 'a', 1 'b', 2 'c'
let sum = 0; [1,2,3].forEach(n => sum += n); console.log(sum); Logs: 6
console.log([1,2,3].forEach(x => x * 2)); Logs: undefined (forEach returns undefined)
[1,,3].forEach(v => console.log(v)); Logs: 1, 3 (skips empty slots/holes)
Gotcha
Returns undefined and cannot be chained. You cannot break out of forEach with break or return — use for...of or some/every instead.
Related methods
Array.prototype.map
Creates a new array populated with the results of calling a callback on every element of the calling array. Reach for it whenever you want to transform each element 1-to-1 into a new value.
Array.prototype.some
Returns true if the callback returns truthy for at least one element, short-circuiting on the first hit. Reach for it to answer "does anything match?" without walking the full array.
Array.prototype.every
Returns true only if the callback returns truthy for every element, short-circuiting on the first falsy result. Reach for it to validate that all items meet a condition.
Array.prototype.filter
Creates a new array containing every element for which the callback returned a truthy value. Reach for it to pare a list down to items matching a predicate.
Array.prototype.reduce
Runs a reducer function on each element, left-to-right, folding the array into a single accumulated value. Reach for it to sum/product/group/build an object or any custom fold.