Skip to content
Advertisement

Math.max and Math.min NaN on undefined entry

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?

Advertisement

Answer

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
Advertisement