I simply do this:
const ar = [1, 2, 3];
ar.reduce(Math.max, 0); // returns NaN
ar.reduce((a, c) => Math.max(a, c), 0); // returns 3 as expected
Any reason for this behaviour?
I simply do this:
const ar = [1, 2, 3];
ar.reduce(Math.max, 0); // returns NaN
ar.reduce((a, c) => Math.max(a, c), 0); // returns 3 as expected
Any reason for this behaviour?
2
Answers
The callback function to
Array#reduce
is passed 4 arguments: the accumulator, the current element, the index, and the original array. All of these end up being passed toMath.max
.The array itself cannot be converted to a number, so
Math.max
returnsNaN
.ar.reduce(Math.max, 0);
is essentially equivalent to the following code:ar.reduce((a, c) => Math.max(a, c), 0)
uses only the arguments that it needs, so it works correctly.@Unmitigated has clearly explained what’s going on in your code and has shown how to use
Array#reduce
and especiallyMath#max
.Here, I show you can use just
Math#max
: