Javascript Array forEach()

The JavaScript Array forEach() method executes a provided function for each array element.

The syntax of the forEach() method is:

arr.forEach(callback(currentValue), thisArg)

Here, arr is an array.


forEach() Parameters

The forEach() method takes in:

  • callback - The function to execute on every array element. It takes in:
    • currentValue - The current element being passed from the array.
  • thisArg (optional) - Value to use as this when executing callback. By default, it is undefined.

Return value from forEach()

  • Returns undefined.

Notes:

  • forEach() does not change the original array.
  • forEach() executes callback once for each array element in order.
  • forEach() does not execute callback for array elements without values.

Example 1: Printing Contents of Array

function printElements(element, index) {
    console.log('Array Element ' + index + ': ' + element);
}
const prices = [1800, 2000, 3000, , 5000, 500, 8000];

// forEach does not execute for elements without values
// in this case, it skips the third element as it is empty
prices.forEach(printElements);

Output

Array Element 0: 1800
Array Element 1: 2000
Array Element 2: 3000
Array Element 4: 5000
Array Element 5: 500
Array Element 6: 8000

Example 2: Using thisArg

function Counter() {
    this.count = 0;
    this.sum = 0;
    this.product = 1;
}

Counter.prototype.execute = function (array) {
    array.forEach((entry) => {
        this.sum += entry;
        ++this.count;
        this.product *= entry;
    }, this)
}

const obj = new Counter();
obj.execute([4, 1, , 45, 8]);

console.log(obj.count); // 4

console.log(obj.sum); // 58

console.log(obj.product); // 1440

Output

4
58
1440

Here, we can again see that forEach skips the empty element. thisArg is passed as this inside the definition of the execute method of the Counter object.


Recommended Reading: JavaScript Array map()