JavaScript Array forEach()

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>"; 
}

Try it yourself

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;
}

Try it yourself

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;
}

Try it yourself

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:

Parameters Description
currentValue Required. The value of the current element.
index Optional. The array index of the current element.
arr Optional. The array object to which the current element belongs.
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