Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Math.max(...[]) is equal to -Infinity in ES2015?

Math.max([]) would be 0

And [..[]] is []

But why Math.max(...[]) is equal to -Infinity in ES2015?

like image 524
Tychio Avatar asked Mar 10 '17 13:03

Tychio


2 Answers

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
like image 188
Struggler Avatar answered Oct 14 '22 01:10

Struggler


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
like image 32
Me.Name Avatar answered Oct 14 '22 02:10

Me.Name