Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

reduce() and array indices

[2014-03-20] dev, javascript, jslang
(Ad, please don’t block)

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) });
    > a.reduce(function(x, y, i) { console.log(i) }, 0);
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 }
    > [].reduce(add)
    TypeError: Reduce of empty array with no initial value
    > [].reduce(add, 123)

More information on reduce()