Difference between .call() and .apply()

On November 13, 2012, in Javascript, by Anuj Gakhar

This is a very common Javascript question that confuses a lot of people (including me). You can use both function.call() and function.apply() in Javascript to execute a function but what’s the difference?

Let’s look at the documentation of call() and apply() first. According to the documentation, .call() means :-

Calls a function with a given this value and arguments provided individually.

and .apply() means :-

Calls a function with a given this value and arguments provided as an array (or an array like object).

The main difference is the apply() takes arguments as an array and call() takes arguments as comma separated list. e.g. if you were to use apply(), your code would look like this :-
[js]myfunction.apply(valueForThis, [arrayOfArgs])[/js]

Whereas, if you were to use call(), your code would look like this :-
[js]myfunction.call(valueForThis, arg1, arg2, …)[/js]

You can use apply() if you do not know the number of arguments you will be passing or the arguments object is already an array. apply() also works great if you need to run a function on an array. e.g. this code below is applying the max function to every element in the array, in just one line of code.
[js]var numersToCompare = [45, 34, 23, 109, 345, 567];
var maxNumber = Math.max.apply(null, numersToCompare);
console.log(maxNumber); // output is 567[/js]

If you know the number of arguments or there are no arguments to be passed, then you can use call(), since then you just need to “call” the function. e.g. the same code above could/would be written like below using call() :-
[js]var maxNumber = Math.max.call(null, 45, 34, 23, 109, 345, 567);
document.write(maxNumber)​ // output is 567[/js]

So, clearly, in the above example, there is an advantage of using apply() as we don’t need to change the number of arguments or the call to the function, we only need to change the array if we have to. However, there can be other scenarios when using call() would be better, specially when number of arguments are fixed or there are no arguments at all.

I have not tested the performance for these 2, but on some initial reading, it looks like there is not much difference in the performance of the 2 methods. My gut feeling is, that call() may be slightly faster than apply() since an array has to be parsed before the actual running of the function when using apply() but I don’t think this difference would be substantial.



One Response to Difference between .call() and .apply()

  1. Imthiyas Mohamed says:

    Very nice blog. I understood the concept very easily. Thank you!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar