Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
27
rated 0 times [  32] [ 5]  / answers: 1 / hits: 21577  / 13 Years ago, fri, january 13, 2012, 12:00:00

When I type in an array into the parameter of the javascript math minimum and maximum functions, it returns the correct value:


console.log( Math.min( 5 ) ); // 5
console.log( Math.max( 2 ) ); // 2

var array = [3, 6, 1, 5, 0, -2, 3];
var minArray = Math.min( array ); // -2
var maxArray = Math.max( array ); // 6

However, when I use the function with no parameters, it returns an incorrect answer:


console.log( Math.min() ); // Infinity
console.log( Math.max() ); // -Infinity

This one returns false:


console.log( Math.min() < Math.max() );

Why does it do this?


More From » math

 Answers
21

Of course it would, because the start number should be Infinity for Math.min. All number that are lower than positive infinity should be the smallest from a list, if there are no smaller.


And for Math.max it's the same; all numbers that are larger than negative infinity should be the biggest if there are no bigger.


So for your first example:


Math.min(5) where 5 is smaller than positive infinity (Infinity) it will return 5.


Update


Calling Math.min() and Math.max with an array parameter may not work on every platform. You should do the following instead:


Math.min.apply(null, [ 1, 2, 3, 4 , 5 ]);

Where the first parameter is the scope argument. Because Math.min() and Math.max() are "static" functions, we should set the scope argument to null.


[#88039] Thursday, January 12, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madelyn

Total Points: 449
Total Questions: 100
Total Answers: 100

Location: Seychelles
Member since Fri, May 7, 2021
3 Years ago
madelyn questions
Wed, Jul 28, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
Sat, Nov 7, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;