JavaScript
Article
By Andrew Tetlaw

What’s the difference between function.call and function.apply?

By Andrew Tetlaw

ButterflyToday I read a great blog post by Mark Needham titled JavaScript: Confusing ‘call’ and ‘apply’. A while back I wrote an article for our Tech Times newsletter about the JavaScript arguments object. It was called arguments: A JavaScript Oddity because it has all sorts of interesting behaviors that are useful to know about. I realized that although I’d used both call and apply in that article I hadn’t talked about the difference.

Well it’s actually quite simple. First of all, both methods expect a thisArg as the first argument. This is the argument that gives the function a context; it determines the value of the JavaScript keyword this inside the function that is called or applied. The single difference is that the call method requires that arguments are specified separately; the apply method takes them as an array. It’s clearer if you see the syntax:

function.call(thisArg[, argument1[, argument2[, ...]]]);
function.apply(thisArg[, argumentArray]);

So if you’re working with the arguments object in your JavaScript, you can call any function by using the apply method and simply pass in the existing arguments object as the array argument.

--ADVERTISEMENT--

Hope that’s useful to you!

Feature image by Sudhamshu. Can you work out the significance?

  • quazecoatl

    I think you might get confused about what brackets mean here
    [, argumentArray]

    This is not an array! It’s not an example of real code! It’s just a notation saying whatever is within the brackets is optional.

    For example, if I have a function myFunc:

    function myFunc(p) {
    console.log(p);
    }

    I could use ‘call’ and ‘apply’ like this:

    myFunc.call(null, 1, 2, 3); // prints out 1
    myFunc.apply(null, [1, 2, 3]); // prints out [1,2,3]

    • Leonid Margolin

      The second also prints out 1

      • quazecoatl

        You’re right.

        Calling myFunc.apply(null, [1, 2, 3]); prints out 1, not [1,2,3]

Recommended
Sponsors
Get the latest in JavaScript, once a week, for free.