🤯 50% Off! 700+ courses, assessments, and books

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

    Andrew Tetlaw
    Share

    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.

    Hope that’s useful to you!

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