JavaScript: Difference between Apply and Call

The Apply() method calls a function with a given this value and arguments provided as an array

The Call() method calls a function with a given this value and arguments provided individually.

Basically, they differ on how they handle function arguments. Apply() lets you invoke the function with arguments as an array, whereas Call() requires the parameters be listed explicitly.

A useful mnemonic is “A for array and C for comma.”

Pseudo syntax:

Sample code:

To answer the part about when to use each function, use apply if you don’t know the number of arguments you will be passing, or if they are already in an array or array-like object (like the arguments object to forward your own arguments. Use call otherwise, since there’s no need to wrap the arguments in an array.

There shouldn’t be any performance differences, except maybe if use apply and wrap the arguments in an array (e.g. f.apply(thisObject, [a, b, c]) instead of f.call(thisObject, a, b, c)).

Resource:

Leave a Reply

Your email address will not be published. Required fields are marked *

CAPTCHA