JavaScript array iteration methods (Part I)

A quick review of The JavaScript Array API’s iteration methods:

Create a simple function:

var plusOne = function (val) { return val + 1; };

Obviously, plusOne(2); yields 3, plusOne(9); yields 10, etc.

Now let’s call plusOne() on each value in this array using Array#map:

var arr = [0,1,2,3,4];
var plusOneArr = arr.map(plusOne);

plusOneArr equals [1,2,3,4,5], as you can verify as follows:

JSON.stringify(plusOneArr) === JSON.stringify([1, 2, 3, 4, 5]);

Now, let’s look at Array#forEach:

var sum = 0;
var addToSum = function (val) { sum = sum + val; };
arr.forEach(addToSum);
console.log(sum);

The value of sum is now 10. But there’s a better way to calculate this, using Array#reduce:

var addToRunningCount = function (runningCount, newVal) { return runningCount + newVal; };
arr.reduce(addToRunningCount, 0);

This returns the value 10 in two lines, versus the previous four lines. Array#reduce takes a callback and a starting value (here 0). If we had wanted to multiply the numbers 1 through 5 together, we could have done the following:

var currentVal = function (prevVal, newVal) { return prevVal * (newVal + 1) };
arr.reduce(currentVal, 1);

This returns 120 (1*2*3*4*5). arr passes in 0, then 1, then 2, etc. up to 4. Each iteration, this becomes newVal. We add one to it, then multiply it by the return value of the last iteration. So it goes: 1, 2, 6, 24, 120.

Remember our old friend?

var plusOne = function (val) { return val + 1; };

Well, we could use this to compose the solution above, rather than hardcode newVal + 1:

var currentVal = function (prevVal, newVal) { return prevVal * plusOne(newVal) };
arr.reduce(currentVal, 1);

This gives the same result, 120. We could instead have used “partial application,” passing plusOne into a function that returns a function, like this:

var modifiableCurrentVal = function (modifier) {
  return function (prevVal, newVal) { return prevVal * modifier(newVal) };
};
var currentVal = modifiableCurrentVal(plusOne);
arr.reduce(currentVal, 1);

For a nice write-up on partial application in Javascript, see this Ben Alman post.

Posted by James on Thursday, March 21, 2013