English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JavaScript Array forEach() Method

 JavaScript Array Object

forEach()The method executes the provided function (callback function) once for each array element.

There is no other way to stop or interrupt the loop except by throwing an exception.forEach()Loop.

If you want to terminate early, you can do so by using the following method:

  • A simple loop

  • Onefor......ofLoop

Syntax:

array.forEach(callback, thisArg)
var fruits = ["Apple", "Mango", "Banana", "Orange"];
var result = document.getElementById("result");
fruits.forEach(function(element) {
    result.innerHTML += element + "<br>";
});
Test and see‹/›

Browser compatibility

The numbers in the table specify the first browser version that fully supports the forEach() method:

Method
forEach()Is1.5IsIs9

Parameter value

ParameterDescription
callback
A function that is run for each element in the array.
Function parameters:
  • currentValue(Required)-The current element being processed in the array

  • index(Optional)-The index of the current element being processed in the array

  • array(Optional)- CalledforEachArray

thisArg(Optional) ExecuteCallbackIs used asThisObject

Technical details

Return value:Undefined
JavaScript version:ECMAScript 5

More examples

The callback function can contain at most3A parameter:

var fruits = ["Apple", "Mango", "Banana", "Orange"];
var result = document.getElementById("result");
fruits.forEach(function(element, index, array) {
    result.innerHTML += index + : "" + element + "<br>";
});
Test and see‹/›

Get the sum of all values in the array:

var nums = [2, 5, 10, 5, 10, 28];
var sum = 0;
nums.forEach(function(element) {
    sum += element;
});
document.getElementById("result").innerHTML = sum;
Test and see‹/›

Get the average value of the values in the array:

var nums = [2, 5, 10, 5, 10, 28];
var sum = 0;
nums.forEach(function(element) {
    sum += element;
});
document.getElementById("result").innerHTML = sum / nums.length;
Test and see‹/›

Convert forEach loop to for loop:

var nums = [2, 5, 10, 5, 10, 28];
var sum = 0;
for (let i = 0; i < nums.length;++) {
    sum = sum + nums[i];
});
document.getElementById("result").innerHTML = sum;
Test and see‹/›

 JavaScript Array Object