Array.prototype.forEach
Runs a function for every element of an array.
Available since: ES5
Syntax
array.forEach(callbackFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A function that receives the element, its index and the whole array. |
Return value
undefinedThe method returns nothing.
Examples
An action for each element:
['tea', 'coffee'].forEach((item) => {
console.log(item);
});Output:
tea
coffeeThe function receives the index as its second argument:
['tea', 'coffee'].forEach((item, index) => {
console.log(index + 1 + '. ' + item);
});Output:
1. tea
2. coffeeNotes
forEach() cannot be stopped early: break does not work in it. Use for...of when you need to exit the loop.
See also
- Array.prototype.map — Creates a new array by transforming every element.
- for...of — Loops over the values of arrays, strings, Maps, Sets and other iterables.
- Array.prototype.entries — Returns index–element pairs for a for...of loop.
Related recipes
In the tutorial
- Iterating over arrays — How to go through every element of an array in JavaScript: the for loop, for...of, forEach and entries.