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:

1 answer
0 points
Answered by:
Admin Dirask Community
4380

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 (...)

Note:

The spread syntax was introduced in ES6.

2. Manually specify each argument without using an array

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

 

See also

  1. JavaScript - ECMAScript / ES versions and features

References

  1. Spread syntax (...) - JavaScript | MDN
  2. Function.prototype.apply() - JavaScript | MDN
0 commentsAdd 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