Reputation: 627
Math.max([])
would be 0
And [..[]]
is []
But why Math.max(...[])
is equal to -Infinity
in ES2015?
Upvotes: 18
Views: 11146
Reputation: 11
When finding out what the biggest number is, where do you start? The answer is the lowest number, -Infinity
function max (array) {
var highest = -Infinity;
foreach(elem in array) if (elem > highest) highest= elem;
return highest;
}
Not accurate code but you get the gist, credit to my friend since the internet let me down once again.
Upvotes: 1
Reputation: 682
FTR the way to get around this is to use a MIN value with the spread operator. Like:
Math.max(MIN_VALUE, ...arr)
Math.max(0, ...[]) --> 0
Math.max(0, ...[1]) --> 1
Math.max(0, ...[23,1]) --> 23
Upvotes: 4
Reputation: 12544
What happens with Math.max([])
is that []
is first converted to a string and then to a number. It is not actually considered an array of arguments.
With Math.max(...[])
the array is considered a collection of arguments through the spread operator. Since the array is empty, this is the same as calling without arguments.
Which according to the docs produces -Infinity
If no arguments are given, the result is -Infinity.
Some examples to show the difference in calls with arrays:
console.log(+[]); //0 [] -> '' -> 0
console.log(+[3]); //3 [] -> '3' -> 3
console.log(+[3,4]); //Nan
console.log(...[3]); //3
console.log(...[3,4]); //3 4 (the array is used as arguments)
console.log(Math.max([])); //0 [] is converted to 0
console.log(Math.max()); // -infinity: default without arguments
console.log(Math.max(...[])); // -infinity
console.log(Math.max([3,4])); //Nan
console.log(Math.max(...[3,4])); //4
Upvotes: 12
Reputation: 67207
If you see the internal implementation documentation, you can tell why Math.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.
Upvotes: 4
Reputation: 2034
If you look at the babel output for Math.max(...[])
, you end up with Math.max.apply(Math, [])
. If you log that in ES5, you see that for some reason it gives you -Infinity
, because it's the same as calling it without an argument.
And indeed, Math.max()
gives -Infinity
If you need a reminder: fn.apply( yourThis, [ a, b, c ] )
is the same as fn( a, b, c )
Upvotes: 3
Reputation: 4239
Because Math.max(...[])
is not Math.max([...[]])
. In the first case, what You really call is Math.max()
, which is -Infinity
. See the spread operator in function call - https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Operators/Spread_operator
Upvotes: 2