Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I write [1,2,3].reduce(Math.max) in Javascript? [duplicate]

Possible Duplicate:
How to use Math.max, etc. as higher-order functions

Using Mozilla's Javascript 1.6 array 'extension' functions (map, reduce, filter etc.), why is it that the following works as expected:

var max = [1,2,3].reduce(function(a,b) { return Math.max(a,b); });

But the following does not work (it produces NaN):

var max2 = [1,2,3].reduce(Math.max);

Is it because Math.max is a variadic function?

like image 563
sacheie Avatar asked Jul 25 '11 19:07

sacheie


People also ask

How to find maximum number in JavaScript?

max() The Math. max() function returns the largest of the zero or more numbers given as input parameters, or NaN if any parameter isn't a number and can't be converted into one.

How to find maximum number in an array in js?

Get the max value in the array, using the Math. max() method. Call the indexOf() method on the array, passing it the max value. The indexOf method returns the index of the first occurrence of the value in the array or -1 if the value is not found.

How does Math max work?

The Math. max() method is used to return the largest of zero or more numbers. The result is “-Infinity” if no arguments are passed and the result is NaN if at least one of the arguments cannot be converted to a number. The max() is a static method of Math, therefore, it is always used as Math.

Why is math Max negative infinity?

max is returning -Infinity when there is no argument passed. If no arguments are given, the result is -∞. So when you spread an empty array in a function call, it is like calling the function without an argument. But the result is negative infinity, not positive.


1 Answers

Math.max does not know what to do with all the extra variables function(previousValue, currentValue, index, array) mainly that array at the end.

[].reduce.call([1,2,3,6],function(a,b) { return Math.max(a,b); });

This works and uses .call

like image 168
Joe Avatar answered Oct 10 '22 21:10

Joe