top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Difference between .call and .apply?

+1 vote
273 views
Difference between .call and .apply?
posted Jan 22, 2015 by Vrije Mani Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

.call() means :-

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

.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.

Example: if you were to use apply(), your code would look like this :-

myfunction.apply(valueForThis, [arrayOfArgs])

Whereas, if you were to use call(), your code would look like this :-

myfunction.call(valueForThis, arg1, arg2, ...)

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.

var numersToCompare = [45, 34, 23, 109, 345, 567];
var maxNumber = Math.max.apply(null, numersToCompare);
console.log(maxNumber); // **output** is 567

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() :-

var maxNumber = Math.max.call(null, 45, 34, 23, 109, 345, 567);
document.write(maxNumber)​ // **output** is 567

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()

answer Jan 23, 2015 by Manikandan J
...