Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Array.reduce on an array with a single element in Javascript

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?

like image 406
fat Avatar asked Nov 24 '15 17:11

fat


People also ask

Can you use reduce on array of objects?

reduce applied to objects. Remember that Array. reduce can use initial and return values of any type, which makes it very flexible.

What is array [- 1 in JavaScript?

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).

How do you call reduce on an array of objects to sum their properties?

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.


1 Answers

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.

like image 128
Alnitak Avatar answered Oct 11 '22 05:10

Alnitak