it is also possible to have it as the first element of the array, as it behaves the same, means same.
Well, no. reduce
is a generic function and supposed to work with arbitrary arrays, not just those that have our expected value as the first element of the array. The most important case would be empty arrays here.
Yes, it would be possible to push (unshift
) the initial value as the first element of the array, then call reduce
without the initial value, then remove it again from the array and you'd have the same result. But this is cumbersome, and might not always work (e.g. with immutable arrays). Also the accumulator might not even have the same type as the array elements.
Just think of the implementation of reduce
, and the pattern which it is supposed abstract:
function reduce(callback, iterable) {
let val = ???;
for (const element of iterable)
val = callback(val, element);
return val;
}
Taking the ???
as a parameter is the sensible choice.