0

How do I use .forEach instead of a for loop?

'use strict';

var score = (function(){
        function updateScore() {
            for(var i = 0; i < arguments.length; i++) {
                this.score += arguments[i];
            }// I want to use .forEach here instead of for loop.
            return this.score;
        }

        return {
            update: updateScore
        }
})();

var soccer = {
    name: 'Soccer',
    score: 0
}

score.update.apply(soccer, [1,2,3])

console.log(soccer.score)

this will log 6.

I tried this

function updateScore() {
  arguments.forEach((args, i) => {
    this.score += args[i];
  };
  return this.score;
}; 

Error log: arguments.forEach is not a function

ken
  • 286
  • 1
  • 5
  • 13

1 Answers1

6

In modern (ES2015) JavaScript you can use Array.from():

Array.from(arguments).forEach((arg) => {
  this.score += arg;
});

You don't need to use array indexing, as the .forEach() function passes each array element to the callback function as the first argument. (It does pass the index as the second argument, but in this case you wouldn't need to use that.)

It's important to note that if the arguments object is passed out of a function (as it would be here), the overall function may be considered ineligible for optimization. That's because the arguments object has some weird properties that make it very hard for the optimizer to know what's going on and whether it's safe to make assumptions about how local variables change. If that's a concern, then the only option is to copy the arguments into a simple array with a for loop.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • This was very helpful! It worked. 7 more minutes before I can check it. Thanks! – ken Jan 16 '16 at 21:48