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

Math.max([]) will be 0

And [..[]] is []

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

+6
source share
5 answers

What happens to Math.max([]) is that [] first converted to a string and then to a number. In fact, it is not considered an array of arguments.

With Math.max(...[]) array is considered a collection of arguments through the spread operator. Since the array is empty, it is the same as calling without arguments. What according to docs creates -Infinity

If no arguments are given, the result is -Infinity.


Some examples showing 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 
+4
source

If you see the documentation internal implementation , you can say why Math.max returns -Infinity when the argument is not passed.

If no arguments are given, the result is -∞.

So, when you propagate an empty array in a function call, it is like calling a function without an argument.

+3
source

If you look at the babel output for Math.max(...[]) , you get Math.max.apply(Math, []) . If you register this with ES5, you will see that for some reason it gives you -Infinity , because it is the same as calling without an argument.

And indeed, Math.max() gives -Infinity

If you need a reminder: fn.apply( yourThis, [ a, b, c ] ) same as fn( a, b, c )

+3
source

Because Math.max(...[]) not Math.max([...[]]) . In the first case, what you really call is Math.max() , which is -Infinity . See the spread operator when calling the function - https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Operators/Spread_operator

+2
source

The FTR way around this is to use the MIN value with the distribution operator. Like:

 Math.max(MIN_VALUE, ...arr) Math.max(0, ...[]) --> 0 Math.max(0, ...[1]) --> 1 Math.max(0, ...[23,1]) --> 23 
0
source

Source: https://habr.com/ru/post/1265293/


All Articles