JavaScript Array forEach() Method

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.


array.forEach(function(currentValue, index, arr), thisValue)

Parameters: This method accepts five parameters as mentioned above and described below:

  • callback: This parameter holds the function to be called for each element of the array.
  • element: The parameter holds the value of the elements being processed currently.
  • index: This parameter is optional, it holds the index of the current value element in the array starting from 0.
  • array: This parameter is optional, it holds the complete array on which Array.every is called.
  • thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.

Return value: The return value of this method is always undefined. This method may or may not change the original array provided as it depends upon the functionality of the argument function.


var sum = 0;
var numbers = [65, 44, 12, 4];

function myFunction(item) {
  sum += item;
  document.getElementById("demo").innerHTML = sum;

Example -