2

I have this following function, where Math.max() is not working as expected. It is always alerting the 1st value from the arguments that are passing. Where is the mistake?

function large(arr) {
   alert(Math.max(arr))
}

large(1,2,3,4,5);

3
  • 3
    Did you have a look at the documentation? Commented Dec 19, 2016 at 5:19
  • max doesn't accept an array as input. so Math.max(arraylist) will return NaN Commented Dec 19, 2016 at 5:20
  • You're not passing an array; you're passing five separate arguments and giving the name arr to the first argument. The other argument values are only accessible through the arguments keyword. Commented Dec 19, 2016 at 5:25

2 Answers 2

8

You are passing multiple arguments, but your function only uses the first one.

In ES5 and before, you can use the apply method of a function and the arguments object:

function large() { 
   alert(Math.max.apply(Math, arguments)) 
} 

large(1,2,3,4,5);

In ES6 you can use the rest and spread operator:

function large(...arr) { 
   alert(Math.max(...arr)) 
} 

large(1,2,3,4,5);

Sign up to request clarification or add additional context in comments.

5 Comments

@Mahi It allows you to call a function with an array (or array-like object) of arguments, with an unknown length.
Should probably specify that it's Function.prototype.apply() in use, here.
@Walf Sure thing.
Note that you're using rest parameter syntax as well as the spread operator.
@nnnnnn Very true.
1

You can do like this.

If you want to use the arguments you can avoid the parameter of the function. Then use the apply function to call Math.max

function large() {
var _max = Math.max.apply(Math, arguments);
alert(_max)
};
large(1, 2, 3, 4, 5, 20,9000);

DEMO

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.