Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

How I remember the difference between and Function.apply

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

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;

But as soon as you need to pass arguments…

 function executeWith123(func, context) {
    // these two statements also have the same effect, 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.

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *