Berk U.
Berk U.

Reputation: 7188

Why does Math.min([1,2]) return NaN?

I've been debugging this code for about an hour, and it looks like Math.min([1,2]) returns NaN.

var int_array = [1,2]
console.log(Math.min(int_array)) //prints NaN, but expect 1
isNaN(Math.min(int_array))===true

Upvotes: 13

Views: 13659

Answers (3)

Rion Williams
Rion Williams

Reputation: 76577

The Math.min() function actually expects a series of numbers, but it doesn't know how to handle an actual array, so it is blowing up.

You can resolve this by using the spread operator ...:

var int_array = [1,2];
console.log(Math.min(...int_array)); // returns 1

You could also accomplish this via the Function.apply() function that would essentially do the same thing but isn't as pretty :

var int_array = [1,2];
console.log(Math.min.apply(null,int_array)); // returns 1

Upvotes: 38

c-smile
c-smile

Reputation: 27470

This

var int_array = [1,2];
console.log(Math.min.apply(null,int_array));

will work in all actual browsers.

Upvotes: 0

isvforall
isvforall

Reputation: 8926

You pass an array as first parameter to min function

Math.min([1,2])

From MDN

If at least one of arguments cannot be converted to a number, the result is NaN.

Upvotes: 5

Related Questions