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?
max() starts with a search value of -Infinity , because any other number is going to be greater than -Infinity. Similarly, Math. min() starts with the search value of Infinity : “If no arguments are given, the result is Infinity .
when you execute Math. min(), you will get (Infinity) and when you execute Math. max(), you will get (-Infinity). by this result for sure if you compare Math.
min() method, the argument is compared with infinity and the passed value is returned. This is because when we compare any number to infinity, infinity will always be the higher value; so, the number becomes the min value. If we don't pass in any argument to the Math. max() method, it will return -Infinity .
min() The static function Math. min() returns the lowest-valued number passed into it, or NaN if any parameter isn't a number and can't be converted into one.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With