Apply?

Hello!

I found the following code to be used to find the maximum of an array of values. I understand the concept of the array object in addition to Math.max but this is the first time that I’ve seen “apply” and I’m not sure how this particular code does what it does. If someone wouldn’t mind giving me a quick explanation, I’d appreciate it.

Array.max = function( array ){
    return Math.max.apply( Math, array );
};

Thanks so much,

Eric

Math.max expects any number of number arguments, and returns the largest number of those arguments.

Math.max(1,2,3) returns 3.

If you passed it an array of numbers (Math.max([1,2,3]) it would return NaN, since an array is not a number.

Calling Math.max.apply(Math,[1,2,3]) calls Math.max with the array passed as its arguments, just like Math.max(1,2,3).

I find examples the easiest to learn from:

.apply() is especially useful for functions that can take multiple arguments (like Math.max). It’s also useful in that it can accept a context as it’s first argument which will scope the functions ‘this’ variable, and the arguments can be programmatic-ally altered without changing the implementation of the function.

Thanks for the help!

-Eric