JavaScript Array forEach() Method
Example
List each item in the array:
var fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
function myFunction(item, index) {
document.getElementById("demo").innerHTML
+= index + ":" + item + "<br>";
}
Try it Yourself »
More "Try it Yourself" examples below.
Definition and Usage
The forEach()
method calls a function once for each element in an
array, in order.
Note: the function is not executed for array elements without values.
Browser Support
The numbers in the table specify the first browser version that fully supports the method.
Method | |||||
---|---|---|---|---|---|
forEach() | Yes | 9.0 | 1.5 | Yes | Yes |
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
Parameter Values
Parameter | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | Required. A function to be run for each element in the array. Function arguments:
|
||||||||
thisValue | Optional. A value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value |
Technical Details
Return Value: | undefined |
---|---|
JavaScript Version: | ECMAScript 5 |
More Examples
Example
Get the sum of all the values in the array:
var sum = 0;
var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction);
function myFunction(item) {
sum += item;
document.getElementById("demo").innerHTML = sum;
}
Try it Yourself »
Example
For each element in the array: update the value with 10 times the original value:
var numbers = [65, 44, 12, 4];
numbers.forEach(myFunction)
function
myFunction(item, index, arr) {
arr[index] = item * 10;
}
Try it Yourself »
Related Pages
JavaScript Tutorial: JavaScript Arrays
JavaScript Tutorial: JavaScript Array Iteration