Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
81
rated 0 times [  83] [ 2]  / answers: 1 / hits: 21775  / 12 Years ago, thu, october 18, 2012, 12:00:00

When passing values to the Math.max or Math.min function in JavaScript, they return the highest and lowest values from the input respectively.


However, if a piece of data that is undefined is entered, e.g.


Math.max(5,10,undefined);

The result returned is NaN. Is there a simply way to fix this using JS/jQuery?


More From » jquery

 Answers
29

I assume the undefined is actually some variable.



You can substitute -Infinity for any NaN value to ensure a number.



var foo;

Math.max(5, 10, isNaN(foo) ? -Infinity : foo); // returns 10


Same concept can be used on Math.min, but with Infinity:



var foo;

Math.min(5, 10, isNaN(foo) ? Infinity : foo); // returns 5

[#82493] Tuesday, October 16, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
josefn

Total Points: 251
Total Questions: 93
Total Answers: 84

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;