Skip to content

Array forEach()

JavaScript Array forEach() Definition

The forEach () method is used to execute a function on each element in an array. In other words: forEach (), the ForEach () method runs a function once provided for each array element.

Let’s try to understand how it works with an example:

        let list = ["row1", "row2", "row3", "row4"];

        let arr = list.forEach(x => console.log(x))

row1
row2
row3
row4

forEach () executes the callback function once for each array element; Not like map () or reduce ().
forEach () does not change the array to which it is called.


JavaScript Array forEach() Syntax

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

currentValue(Required): The value of the current element.
index(Optional) : The array index of the current element.
arr (Optional): The array object the current element belongs to.


JavaScript Array forEach() Examples

Example 1

Let’s write a code using the for() loop:

        let cars = ["bmw", "audi", "toyota", "skoda"];
        let newCarsList = [];

        for (var i = 0; i < cars.length; i++) {
            newCarsList += (cars[i]+",")
        }

        console.log(newCarsList)

output:

bmw,audi,toyota,skoda

We can write this without using a loop. using the forEach() method:

        let cars = ["bmw", "audi", "toyota", "skoda"];
        let newCarsList = [];

        cars.forEach(function (i) {
            newCarsList += (i+",")
        });

        console.log(newCarsList)

output:

bmw,audi,toyota,skoda


Example 2

        var total = 0;
        var numbers = [10, 10, 10, 10];

        function result(x) {
            total += x;
            console.log(total)
        }
        numbers.forEach(result)

output:

10
20
30
40


Example 3

        let numberList = [5, 10, 15, 20, 25];
        let result = [];

        numberList.forEach(function (numberList) {
            result = (numberList * numberList)
            console.log(result)
        })

output:

25
100
225
400
625


Example 4

        var days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];

        days.forEach(function (element, index) {
            if (element[0] == "T") {
                alert(element + " " + index + ". rank.");
            }
        });

output:

Tuesday 1. rank
Thursday 3. rank


Pollyfill

if (!Array.prototype.forEach) {

  Array.prototype.forEach = function(callback/*, thisArg*/) {

    var T, k;

    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    // 1. Let O be the result of calling toObject() passing the
    // |this| value as the argument.
    var O = Object(this);

    // 2. Let lenValue be the result of calling the Get() internal
    // method of O with the argument "length".
    // 3. Let len be toUint32(lenValue).
    var len = O.length >>> 0;

    // 4. If isCallable(callback) is false, throw a TypeError exception. 
    // See: http://es5.github.com/#x9.11
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }

    // 5. If thisArg was supplied, let T be thisArg; else let
    // T be undefined.
    if (arguments.length > 1) {
      T = arguments[1];
    }

    // 6. Let k be 0.
    k = 0;

    // 7. Repeat while k < len.
    while (k < len) {

      var kValue;

      // a. Let Pk be ToString(k).
      //    This is implicit for LHS operands of the in operator.
      // b. Let kPresent be the result of calling the HasProperty
      //    internal method of O with argument Pk.
      //    This step can be combined with c.
      // c. If kPresent is true, then
      if (k in O) {

        // i. Let kValue be the result of calling the Get internal
        // method of O with argument Pk.
        kValue = O[k];

        // ii. Call the Call internal method of callback with T as
        // the this value and argument list containing kValue, k, and O.
        callback.call(T, kValue, k, O);
      }
      // d. Increase k by 1.
      k++;
    }
    // 8. return undefined.
  };
}

Browser Support

Chromeyes
Edgeyes
Firefox1.5
Internet Explorer9
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes

3 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: