Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why calling apply on Math.max works and without it doens't

Tags:

javascript

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.

like image 586
james emanon Avatar asked Aug 31 '13 08:08

james emanon


People also ask

Why is math MAX () less than math MIN ()?

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 .

What does math Max apply do?

The Math.max() function returns the largest of the numbers given as input parameters, or - Infinity if there are no parameters.

What is the difference between math min and math Max?

Math. min() to find the minimum of n elements. Math. max() to find the maximum of n elements.

Does math max work on arrays?

The Math. max() method compares the variable max with all elements of the array and assigns the maximum value to max .


1 Answers

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.

like image 72
Arash Milani Avatar answered Nov 14 '22 23:11

Arash Milani