JavaScript Array forEach()
Example 1
Calls a function for each element in fruits:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
Try it Yourself »
fruits.forEach(myFunction);
Description
The forEach()
method calls a function for each element in an array.
The forEach()
method is not executed for empty elements.
Array Iteration Methods:
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
Parameters
function()
Required.
A function to run for each array element.
A function to run for each array element.
currentValue
Required.
The value of the current element.
The value of the current element.
index
Optional.
The index of the current element.
The index of the current element.
arr
Optional.
The array of the current element.
The array of the current element.
thisValue
Optional. Default
A value passed to the function as its
undefined
.A value passed to the function as its
this
value.
Return Value
undefined
More Examples
Compute the sum:
let sum = 0;
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Try it Yourself »
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
}
Multiply each element:
const numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function myFunction(item, index, arr) {
arr[index] = item * 10;
}
Try it Yourself »
numbers.forEach(myFunction)
function myFunction(item, index, arr) {
arr[index] = item * 10;
}
Array Tutorials:
Browser Support
forEach()
is an ECMAScript5 (ES5 2009) feature.
JavaScript 2009 is supported in all browsers since July 2013:
Chrome 23 |
IE/Edge 11 |
Firefox 21 |
Safari 6 |
Opera 15 |
Sep 2012 | Sep 2012 | Apr 2013 | Jul 2012 | Jul 2013 |