Why is math.max() returning NaN on an array of integers?

39,073

Solution 1

It's not working because you are passing an array as the parameter instead of comma separated numbers. Try spreading the array like this:

data = [4, 2, 6, 1, 3, 7, 5, 3];    
alert(Math.max(...data));

Solution 2

If you have to use the Math.max function and one number of the array might be undefined, you could use:

x = Math.max(undefined || 0, 5)
console.log(x) // prints 5
Share:
39,073
Matt Welander
Author by

Matt Welander

Updated on July 05, 2022

Comments

  • Matt Welander
    Matt Welander almost 2 years

    I am trying to get the highest number from a simple array:

    data = [4, 2, 6, 1, 3, 7, 5, 3];
    
    alert(Math.max(data));
    

    I have read that if even one of the values in the array can't be converted to number, it will return NaN, but in my case, I have double-checked with typeof to make sure they are all numbers, so what can be my problem?