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.
max() starts with a search value of -Infinity , because any other number is going to be greater than -Infinity. Similarly, Math. min() starts with the search value of Infinity : “If no arguments are given, the result is Infinity .
The Math.max() function returns the largest of the numbers given as input parameters, or - Infinity if there are no parameters.
Math. min() to find the minimum of n elements. Math. max() to find the maximum of n elements.
The Math. max() method compares the variable max with all elements of the array and assigns the maximum value to max .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With