Why should use “apply”?

In this case, the log function may accept any number of arguments.

Using .apply(), it doesn’t matter how many arguments are passed. You can give the set to console.log(), and they will arrive as individual arguments.

So if you do:

console.log(arguments)

…you’re actually giving console.log a single Arguments object.

But when you do:

console.log.apply( console, arguments );

…it’s as though you passed them separately.

Other useful examples of using .apply() like this can be demonstrated in other methods that can accept a variable number of arguments. One such example is Math.max().

A typical call goes like this:

var max = Math.max( 12,45,78 );  // returns 78

…where it returns the largest number.

What if you actually have an Array of values from which you need the largest? You can use .apply() to pass the collection. Math.max will think they were sent as separate arguments instead of an Array.

var max = Math.max.apply( null, [12,45,92,78,4] );  // returns 92

As you can see, we don’t need to know in advance how many arguments will be passed. The Array could have 5 or 50 items. It’ll work either way.

Leave a Comment