Tech Junkie Blog: JavaScript Array Methods: forEach()

Monday, May 14, 2018

JavaScript Array Methods: forEach()

The forEach() method loops through an array, and performs a function on each element of the array.  The forEach() method can take three arguments, the first argument is a current value that you want to perform an action on.  The second argument acts as the "this" value within the scope of the function.  The third argument is the array itself.  Most of the time only the first argument is passed.  The code below passes in only one argument which is an anonymous function being performed on each element of the array using the forEach() method to calculate the oil prices in the last five days and prints it out in the console.


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];
        var total = 0;

        oilPrices.forEach(function (value) { total += value });

        console.log(total);
    </script>

You should get the total of 362.19 as your total when you add up the last five days of oil prices.









If you want to pass in all three values you can have a function that can manipulate the actual value itself like the code below.  Let's say you buy your oil in large quantity so you get a $1 discount for each barrel of oil.  The following forEach() method will show you the discounted oil prices.


    <script>
        var oilPrices = [70.15, 69.50, 71.23, 74.32, 76.99];
        var total = 0;

        oilPrices.forEach(function (value) { total += value });

        console.log(total);

        oilPrices.forEach(function (value, index, prices) { prices[index] = value - 1; });

        console.log(oilPrices);
    </script>

As you can you got yourself a discount













No comments:

Post a Comment