Call Array.reduce for a single element array in Javascript

Calling shorthand on an empty throws array TypeError, which is understandable and helps catch errors. But when I call it an array with one element inside, the behavior confuses me:

var arr = ["a"];
arr.reduce(function(a,b){
   return [a,b]
}); //returns "a"

I know that the abbreviation is not intended to be used in such an array, but I believe that returning only an element without calling a callback or throwing an error is at least strange.

In addition, the MDN documentation states that the callback is "a function for each value in the array, taking four arguments:".

Can someone explain the reasons for this behavior?

+4
source share
1 answer

" " (.. , , currentIndex array).

, undefined currentValue previousValue, .

, , ( initialValue, no initialValue), .

+8

Source: https://habr.com/ru/post/1617301/


All Articles