.forEach()
Published Jun 22, 2021Updated Mar 25, 2023
Contribute to Docs
The .forEach()
array method loops over the array, passing each item in the array into the callback function provided.
Syntax
array.forEach((value, index, array) => {...});
A function can be invoked with three arguments:
value
: The value of the array element.index
(optional): The index of the array element.array
(optional): The array itself.
Note: Unlike a regular for
loop, .forEach()
method does not provide a way to terminate iteration before all elements have been passed to the function.
Example 1
Logging each value in an array:
['a', 'b', 'c'].forEach((letter) => console.log(letter));
The output would be:
abc
Example 2
Finding the sum of an array:
const values = [7, 17, 34, 41, 22, 5];let sumOfValues = 0;values.forEach((value) => (sumOfValues += value));console.log(sumOfValues);// Output: 126
Codebyte Example
The following codebyte example multiplies all the values in an array and returns the product:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.