2014-03-20

reduce() and array indices

This blog post explains how the index works that Array.prototype.reduce() passes to its callback.

What indices does the callback receive?

Tobie Langel recently pointed out something about Array.prototype.reduce() that looks odd at first glance (slightly edited by me):
    > var a = [ 'a', 'b', 'c' ];
    > a.reduce(function(x, y, i) { console.log(i) });
    1
    2
    > a.reduce(function(x, y, i) { console.log(i) }, 0);
    0
    1
    2
It does make sense if you look at the signature of the reduce() callback:
    function (previousValue, currentElement, currentIndex, array)
Therefore, what is logged in the example is the index of y.

reduce() and empty arrays

What also suprised me about reduce() is that you can only use it for empty arrays if you provide an initial value (like the second variant above). That value becomes the first previousValue that the callback is invoked with.
    > function add(prev, cur) { return prev + cur }
    undefined
    > [].reduce(add)
    TypeError: Reduce of empty array with no initial value
    > [].reduce(add, 123)
    123

More information on reduce()

No comments: