user1249791
user1249791

Reputation: 1271

function executed by .apply() works with array, but does not the original function

if Math.max([1,3,9]) returns error (needs a list of numbers, not an array), why calling it via apply like below works?

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

getMaxOfArray([1,3,9]) //9 
getMaxOfArray(1,3,9) //error

I understand .apply passes an array, but why should max function work with them only when called via apply? is there some internal transformation array => list ?

Upvotes: 0

Views: 709

Answers (3)

Kevin Ji
Kevin Ji

Reputation: 10489

Your function only accepts one argument (numArray), not three—this is why your call to getMaxOfArray is failing. If you are writing a one-liner, you should use call instead of apply for a series of parameters rather than an array, as so:

Math.max.apply(null, [1, 3, 9]);
Math.max.call(null, 1, 3, 9);

For a function, you can use the arguments object for a variable number of parameters, if you do not want the user to pass an array. Here's how you would go about doing it this way. (Note that I still call apply here, because I store all of the arguments called by the user into an array.)

function getMaxOfArguments() {
   var parameters = 1 <= arguments.length ? [].slice.call(arguments, 0) : [];
   return Math.max.apply(null, parameters);
}

Now, your second function call should work:

getMaxOfArguments(1, 3, 9); // 9

Upvotes: 2

CharlesTWall3
CharlesTWall3

Reputation: 546

The function signature of Math.max is function(arg1, arg2, arg3, ...) not function(Array). Apply is converting the input into a more palatable form for Math.max.

Upvotes: 0

Jeff Storey
Jeff Storey

Reputation: 57192

apply expects the parameters to be in an array. if you just have the parameter list how you do in the second case, use call instead

Math.max.apply(null,[1,3,9])
Math.max.call(null,1,3,9)

What is the difference between call and apply? goes into a good amount of detail on the difference between call and apply

Upvotes: 3

Related Questions