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?

iOS Developer, sometimes web developer and Technical Editor.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

No Reader comments

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.