Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 275
jacktheripper Avatar asked Oct 18 '12 14:10

jacktheripper


People also ask

Why is math MAX () less than math MIN ()?

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 .

What is the difference between math MIN () and math MAX () functions?

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.

How do you use math Max and math min?

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 .

What does math min do in JavaScript?

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.


1 Answers

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
like image 52
I Hate Lazy Avatar answered Sep 22 '22 04:09

I Hate Lazy