javascriptcallbackreduceoptional-parameters

Why does the callback function for reduce take four parameters?


In studying the reduce method I'm not quite sure why the callback passed in needs the third and fourth parameters, index and array. In the example from the MDN:

[0, 1, 2, 3, 4].reduce(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue;
});

A lot of other uses for the array reduce method or underscore reduce function I've studied only make use of the first two parameters for the callback: previousValue (sometimes seen as accumulator) and currentValue (aka elem, the value of the current index).

Why is reduce sometimes written with callback taking four parameters and sometimes written with only previousValue and currentValue?

What would be a case where the index and array parameters are needed?

Should all four parameters always be given in a function definition for reduce in case an application of reduce requires the third or fourth parameters?


Solution

  • here is a (slightly) less-contrived example to sum up unique values in an array, skipping duplicates, using the index and array arguments to find unique values:

    [0, 1, 2, 3, 2, 1, 0].reduce(function(previousValue, currentValue, index, array) {
      return array.indexOf(currentValue) === index ? // value used already?
             previousValue + currentValue :  // not used yet, add to sum
             previousValue; // used already, skip currentValue
    }); // == 6  ( 0+1+2+3 )
    

    live demo: http://pagedemos.com/fn764n659ama/1/

    side note: [].reduce() runs quite a bit faster in V8 by specifying all four arguments as formal parameters on the callback, regardless of if they are used by the code inside the function.