Reputation: 11807
If you asked me to get the max of an array, I would just do:
var nums = [66,3,8,213,965,1,453];
Math.max.apply(Math, nums);
of course, I could also do: nums.sort(function(a, b){ return a - b}.pop(nums.length);
but I have to be honest. I need to know WHY that works - using .apply(Math,nums). If I just did this:
Math.max(nums);
that would not work.
by using apply, I pass in Math as this - and nums for the array. But I want to know the intricacies of "why" that the first works and the latter doesn't. What magic is happening?
There is something fundamental I am not wrapping my brains around. I have read a bunch about "call and apply", but many times some cool tricks can be had like the one above, and I feel I am missing something deeper here.
Upvotes: 5
Views: 691
Reputation: 6308
As you can read here about Function.prototype.apply, apply
Calls a function with a given this
value and arguments provided as an array
. So the second parameter for the apply
function accepts arrays
, that's why it works.
While Math.max() itself expects any number of parameters NOT an array of them:
Math.max(66,3,8,213,965,1,453) //will work
Math.max([66,3,8,213,965,1,453]) //will not work
Usually you will be using apply
for calling functions with dynamic parameters (e.g. user generated) that you don't know the number of parameters. On the other hand if you have a fixed number of parameters then you can easily provide them to Math.max()
function.
Upvotes: 7