JavaScript Array forEach()
- Previous Page flatMap()
- Next Page from()
- Go to the Previous Level JavaScript Array Reference Manual
Definition and usage
forEach()
The method calls the function once for each element in the array in order.
Note:No operation is performed for array elements without values.forEach()
Method.
Example
Example 1
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>"; }
Example 2
Get the sum of all 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; }
Example 3
For each element in the array: update the value to 10 times the original value:
var numbers = [65, 44, 12, 4]; numbers.forEach(myFunction) function myFunction(item, index, arr) { arr[index] = item * 10; }
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
Parameter value
Parameters | Description | ||||||||
---|---|---|---|---|---|---|---|---|---|
function(currentValue, index, arr) | Required. The function to be run for each element in the array.
Function parameters:
|
||||||||
thisValue |
Optional. The 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 |
Browser support
All browsers fully support forEach()
Method:
Chrome | IE | Edge | Firefox | Safari | Opera |
---|---|---|---|---|---|
Chrome | IE | Edge | Firefox | Safari | Opera |
Support | 9.0 | Support | Support | Support | Support |
Related Pages
Tutorial:JavaScript Array
Tutorial:JavaScript Array Const
Tutorial:JavaScript Array Methods
Tutorial:JavaScript Sorting Array
Tutorial:JavaScript Array Iteration
- Previous Page flatMap()
- Next Page from()
- Go to the Previous Level JavaScript Array Reference Manual