Languages

JavaScript - why is Math.max() returning NaN on array of integers?

0 points
Asked by:
mkrieger1
726

I want to get the highest number from an array of numbers but Math.max() method returns NaN.

What did I do wrong?

My code:

// ONLINE-RUNNER:browser;

var numbers = [1, 4, 2, 5, 3];

console.log(Math.max(numbers)); // NaN
1 answer
0 points
Answered by:
mkrieger1
726

Your code doesn't work because Math.max() expects each argument to be a valid number.

From the documentation:
The Math.max() returns NaN if any parameter isn't a number and can't be converted into one.

What you are trying to do is provide one argument that is an array, not a number.

Suggested solutions

1. Use spread syntax (...)

// ONLINE-RUNNER:browser;

var numbers = [1, 4, 2, 5, 3];

console.log(Math.max(...numbers)); // 5

Note:

The spread syntax was introduced in ES6.

2. Manually specify each argument without using an array

// ONLINE-RUNNER:browser;

console.log(Math.max(1, 4, 2, 5, 3)); // 5

3. Explicitly call Math.max() by using apply() method and passing an array of arguments

// ONLINE-RUNNER:browser;

var numbers = [1, 4, 2, 5, 3];

console.log(Math.max.apply(Math, numbers)); // 5

 

See also

  1. JavaScript - ECMAScript / ES versions and features

References

  1. Spread syntax (...) - JavaScript | MDN
  2. Function.prototype.apply() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join