var a = 1;
var b = 2;
if...{var c = 3};
var d = Math.max(a, b, c);
How to get Math.max function work, if some of variables weren’t declared? Choosing the biggest among existing.
var a = 1;
var b = 2;
if...{var c = 3};
var d = Math.max(a, b, c);
How to get Math.max function work, if some of variables weren’t declared? Choosing the biggest among existing.
Anything that you provide to Math.max()
will attempt to be converted to a Number MDN: Math.max()
:
The largest of the given numbers. If at least one of the arguments cannot be converted to a number, NaN is returned.
You are asking that undefined
be convereted to a Number which is difficult since it is undefined. Consider that 0+undefined
returns NaN
and Number(undefined)
also returns NaN
.
If you want Math.max()
to not follow this rule of returning NaN
, then you need to write your own Math.max()
.
Also, per Robby's comment, it would be best to just filter out any undefined
values or any other values that you don't want considered in the max()
.
Maybe something like:
function myMax(...args) {
// Re write this filter to alter whatever you don't want to be considered by max()
return Math.max(...args.filter(e => e !== undefined));
}
console.log(myMax(undefined, 1, 2)); // 2
console.log(myMax(-2, -1, undefined)); // -1
console.log(myMax(undefined)); // -Infinity