I’m trying an obvious task:
var maxVal = [ 1, 2, 3, 4, 5 ].reduce( Math.max, 0 );
and get:
NaN
as the result. To make it work I have to make an anonymous function this way:
var maxVal = [ 1, 2, 3, 4, 5 ].reduce( function ( a, b ) {
return Math.max(a, b);
}, 0 );
Could someone tell me why? Both are functions that take two arguments and both return one value. What’s the difference?
Another example could be this:
var newList = [[1, 2, 3], [4, 5, 6]].reduce( Array.concat, [] );
The result is:
[1, 2, 3, 0, #1=[1, 2, 3], #2=[4, 5, 6], 4, 5, 6, 1, #1#, #2#]
I can run this example in node.js only under this shape (Array has no concat in node.js v4.12, which I use now):
var newList = [[1, 2, 3], [4, 5, 6]].reduce( [].concat, [] );
and then get this:
[ {}, {}, 1, 2, 3, 0, [ 1, 2, 3 ], [ 4, 5, 6 ], 4, 5, 6, 1, [ 1, 2, 3 ], [ 4, 5, 6 ] ]
And why is that?
The function passed to
reducetakes more than 2 arguments:previousValuecurrentValueindexarrayMath.maxwill evaluate all arguments and return the highest:So in case of passing
Math.maxtoreduce, it will return the highest value from the 4 arguments passed, of which one is an array. Passing an array will makeMath.maxreturnNaNbecause an array is not a number. This is in the specs (15.8.2.11):ToNumberwill returnNaNfor an array.So reducing with
Math.maxwill returnNaNin the end.