Math.max([])
would be 0
And [..[]]
is []
But why Math.max(...[])
is equal to -Infinity
in ES2015?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With