EN
JavaScript - why is Math.max() returning NaN on array of integers?
1 answers
0 points
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:
xxxxxxxxxx
1
var numbers = [1, 4, 2, 5, 3];
2
3
console.log(Math.max(numbers)); // NaN
1 answer
0 points
Your code doesn't work because Math.max()
expects each argument to be a valid number.
From the documentation:
TheMath.max()
returnsNaN
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 (...
)
xxxxxxxxxx
1
var numbers = [1, 4, 2, 5, 3];
2
3
console.log(Math.max(numbers)); // 5
Note:
The spread syntax was introduced in ES6.
2. Manually specify each argument without using an array
xxxxxxxxxx
1
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
xxxxxxxxxx
1
var numbers = [1, 4, 2, 5, 3];
2
3
console.log(Math.max.apply(Math, numbers)); // 5
See also
References
0 commentsShow commentsAdd comment