Calling reduce on an empty array throws TypeError
which is perfectly understandable and helps catching bugs. But when I call it on an array with a single item inside, the behavior confuses me:
var arr = ["a"];
arr.reduce(function(a,b){
return [a,b]
}); //returns "a"
I know that reduce is not meant to be used on such an array, but I find that returning just the element without invoking the callback or throwing an error is at least strange.
Furthermore, the MDN documentation states that the callback is a "Function to execute on each value in the array, taking four arguments:".
Can someone explain the reasoning behind this behaviour?
reduce applied to objects. Remember that Array. reduce can use initial and return values of any type, which makes it very flexible.
As others said, In Javascript array[-1] is just a reference to a property of array (like length ) that is usually undefined (because it's not evaluated to any value).
const sum = values. reduce((accumulator, currentValue) => { return accumulator + currentValue; } , 0); As you can see, the reduce method executes the call back function multiple times. For each time, it takes the current value of the item in the array and sum with the accumulator.
The callback is supposed to be a "binary function" (i.e. one that takes two arguments to operate on, plus the additional two arguments that hold the currentIndex
and the original array
).
If only one element is supplied, you would be passing an undefined value to the callback for either currentValue
or previousValue
, potentially causing runtime errors.
The design therefore assumes that given only one value (whether that be an empty array, and an initialValue
, or an array with one value and no initialValue
) it's better not to invoke the callback at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With