Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Math.max() return NaN? [duplicate]

Tags:

javascript

I want to create a function which returns the maximum number from an array, but it keeps returning NaN.

How can I prevent NaN and return the wanted result ?

var thenum = [5,3,678,213];

function max(num){
    console.log(Math.max(num));
}

max(thenum);                                                                      
like image 824
Osiris Avatar asked Feb 11 '23 12:02

Osiris


2 Answers

The reason why this is happening is that Math.max calculates the maximum out of its parameters. And seen as the first parameter is an Array it returns NaN.

You now have 2 options (depending on your environment or preference):

ES6 (with spread syntax)

You can spread the array to the params of the function.

const thenum = [5, 3, 678, 213];

console.log(Math.max(...thenum));

More on the spread syntax

And here is a jsFiddle with this example.


ES5 (without spread syntax)

Or, you can call it using the apply method which allows you to call functions and send the parameters for them within an array.

What you want is to apply the Math.max function, like so:

var thenum = [5, 3, 678, 213];

function max(num){
    return Math.max.apply(null, num);
}

console.log(max(thenum));

You can also make it a method and attach it to the Array prototype. This way you can use it easier and cleaner (overwriting the prototype is dangerous and you should probably avoid it - Read more about it). Like so:

Array.prototype.max = function () {
    return Math.max.apply(null, this);
};
console.log([5, 3, 678, 213].max());

More on the apply method.

And here is a jsFiddle with both

like image 125
Ciprian Mocanu Avatar answered Feb 13 '23 04:02

Ciprian Mocanu


try this one. Math.max.apply(Math,thenum)

var thenum = [5,3,678,213];

function max(num){
    console.log(Math.max.apply(Math,thenum));
}

result: 678

like image 30
Dyrandz Famador Avatar answered Feb 13 '23 03:02

Dyrandz Famador