Math.max and Math.min NaN on undefined entry
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
Write your own max
function:
function max() {
var par = []
for (var i = 0; i < arguments.length; i++) {
if (!isNaN(arguments[i])) {
par.push(arguments[i]);
}
}
return Math.max.apply(Math, par);
}
Or shorter using array filtering:
function max() {
var args = Array.prototype.slice.call(arguments);
return Math.max.apply(Math, args.filter(function(val) {
return !isNaN(val);
}));
}
Usage:
max(5, 10, undefined); // output: 10
Check that each number is defined before passing it to max
. Use an sentinel value as a default (such as -Infinity
). For min you would want to use Infinity
:
var a = 5;
var b = 10;
var c = undefined;
var defaultForMax = function (num) {
return typeof num === 'number' ? num : -Infinity;
};
c = defaultForMax(c); // c is now -Infinity
Math.max(a, b, c); // 10
http://jsfiddle.net/QTckE/
It's as simple as:
// ES6 (returns: 10)
Math.max(...[5, 10, undefined].filter(Number.isFinite))
Or:
// ES5 (returns: 10)
Math.max.apply(null, [5, 10, undefined].filter(Number.isFinite))
I think it is readable, and simply conveys its purpose.
Explanation: We take advantage of the Number
primitive wrapper object
, to filter out the undefined values, and then pass it to the Math.max
function, as arguments with the spread operator in ES6, or with the Function.prototype.apply()
method in ES5.