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.
JavaScript
x
2
1
Math.max(5,10,undefined);
2
The result returned is NaN
. Is there a simply way to fix this using JS/jQuery?
Advertisement
Answer
I assume the undefined
is actually some variable.
You can substitute -Infinity
for any NaN
value to ensure a number.
JavaScript
1
4
1
var foo;
2
3
Math.max(5, 10, isNaN(foo) ? -Infinity : foo); // returns 10
4
Same concept can be used on Math.min
, but with Infinity
:
JavaScript
1
4
1
var foo;
2
3
Math.min(5, 10, isNaN(foo) ? Infinity : foo); // returns 5
4