-3
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.

Presto
  • 31
  • 2

1 Answers1

1

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
zero298
  • 25,467
  • 10
  • 75
  • 100
  • Probably better to filter out the `undefined` values. In your case, if the defined values are negative, `Math.max()` will still return a result of `0`. – Robby Cornelissen Feb 05 '18 at 20:16
  • @RobbyCornelissen You're right, I hadn't considered that test case. Would probably be more performant as well. – zero298 Feb 05 '18 at 20:17