-1

I'm trying to get my head around what JavaScript's apply() method actually does. I'm using this as a reference: http://ejohn.org/blog/fast-javascript-maxmin/, in which apply() is used to give Array a min() function.

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

How does apply() work here? I get that Math.min() can't take an array as an argument, but I'm having trouble visualizing how apply() turns the array into a list of arguments that Math.min understands.

  • 3
    I don't understand what sort of answer you are looking for here. `apply` turns the array into an argument list because that is what `apply` is defined as doing in the JavaScript language specification. How it goes about that is an implementation detail which will vary between JavaScript engines. – Quentin Sep 05 '15 at 22:06
  • Do you know how `apply` works in general? – Bergi Sep 05 '15 at 22:08
  • Also duplicate of [JavaScript Apply](http://stackoverflow.com/q/14791987/1048572) – Bergi Sep 05 '15 at 22:10
  • @Quentin, you know, I'm not sure. I'm always weary of thinking I understand things, so I just use StackOverflow as a place to check what I think I know. I think, though, I'd like to see the source code for `apply()` to understand the actual logic that goes into making it work. Or, maybe, I'll try to code up my own version and go from there. – just another profile name Sep 05 '15 at 22:14

1 Answers1

0

That's exactly what the apply method does. It calls the method with the array items as parameters.

Using Math.min.apply(Math, [ 1, 2, 3 ]) is the same as Math.min(1, 2, 3).

There is nothing special with making it work for the Math.min method, it works the same for any function. Using myFunction.apply(window, ['a','b']) does the same thing as myFunction('a', 'b').

Guffa
  • 687,336
  • 108
  • 737
  • 1,005