Reputation: 26976
Anybody knows why the first works but the second doesn't? (returns NaN)
[1, 2].reduce((a, b) => Math.min(a, b)) // 1
[1, 2].reduce(Math.min) // NaN
I guess it has something to do with the signature of reduce?
Upvotes: 0
Views: 37
Reputation: 375
I had the same query, thankyou for the clear question and answer. One useful comment I saw while looking for the answer; it may well be simpler to use
const a = [1,2]
Math.min(...a)
Upvotes: 0
Reputation: 73251
reduce()
has 4 params in total that it can pass to the callback, Math.min
takes var-arg - (...items
) - as many as you pass items. That means that you'll also pass an array and the index to Math.min. NaN is produced by the array you pass to it, and everything else would be unreliable as you also pass the index.
You can see how it would behave if you pass a reference to a function that only takes two arguments to reduce:
const t = [1, 2].reduce(foo);
function foo(a,b) {
return Math.min(a,b);
}
console.log(t); // 1
Upvotes: 4