How I remember the difference between Function.call and Function.apply

September 4, 2012 Mark Rushakoff

In Javascript, when you use a function as a first-class-object, you can call the function directly without any special context:

 function execute(func) {
     func();
 }

where the context is the value of this in the function when it’s executed.

If you’re not invoking the function with any arguments, it doesn’t really matter whether you use .apply or .call:

function execute(func, context) {
    // these two statements have the same effect
    func.call(context);
    func.apply(context);
}

But as soon as you need to pass arguments…

 function executeWith123(func, context) {
    // these two statements also have the same effect
    func.call(context, 1, 2, 3);
    func.apply(context, [1, 2, 3]);
 }

The difference is that with call, you can write as many arguments as you need, which is handy when you know exactly which and how many arguments you’re passing. With apply, it’s easier to use a variable number of arguments.

I used to have to always look up the difference between call and apply, until I realized:

Function.apply takes an array: A is for Apply and Array.

I hope that saves you the pain of looking up the documentation or guessing and picking the wrong one next time.

About the Author

Biography

More Content by Mark Rushakoff
Previous
Problems with our CDN
Problems with our CDN

As some of you have (painfully) noticed, we've been having problems with our CDN (content distribution netw...

Next
Facebook 5.0 on iOS Shows that Native Wins
Facebook 5.0 on iOS Shows that Native Wins

When we look at the the most influential apps since I wrote “On Native and Web Apps in Mobile” last year, n...