Process every element
Logging, displaying, or otherwise handling each item individually.
JavaScript · Function
Array.prototype.forEach() invokes a callback once for each assigned array element in ascending-index order. It returns undefined and is mainly used to perform side effects.
Call forEach with a callback to process array elements in ascending index order. The callback receives the current element, its index, and the source array; forEach returns undefined, so use it for side effects rather than producing a transformed array.
forEach(callbackFn)
forEach(callbackFn, thisArg)| Name | Type | Description |
|---|---|---|
callbackFn | function | A function invoked once for each assigned array element. It receives element, index, and array arguments; its return value is discarded. |
thisArg | any | Optional value used as this when callbackFn executes. |
None (undefined).
const prices = [10, 15, 20];
const total = { value: 0 };
prices.forEach(function (price) {
this.value += price;
}, total);
console.log(total.value); // 45Adds each price to an accumulator while demonstrating the optional thisArg.
Logging, displaying, or otherwise handling each item individually.
Updating external state or an accumulator during traversal.
Applying an operation to an array-like object that has length and integer-keyed properties.
forEach invokes the callback once for each assigned array element, in ascending-index order. The callback receives the element, index, and array, and the method itself returns undefined.
Follow-up: How would you create a transformed array instead? Use map(), whose callback results form a new array; forEach is intended for side effects.
The optional thisArg supplies the this value used when invoking the callback. This is useful with a traditional function; an arrow function has lexical this and does not take its this from thisArg.
Follow-up: What happens if the callback is async? forEach does not wait for promises, so use an explicit loop when sequential awaiting is required.
forEach is an iterative method for performing an action on each array element, not for constructing a result. It always returns undefined and therefore cannot be chained as a transformation.
Follow-up: Can iteration be stopped normally? No; forEach has no break mechanism, so use a loop or a method such as some(), every(), or find() when early termination is needed.
Array.prototype.map()Array.prototype.filter()Array.prototype.some()Array.prototype.every()Array.prototype.find()TypedArray.prototype.forEach()