What is the difference between call and apply?

Asked : Nov 17

Viewed : 19 times

What is the difference between using Function.prototype.apply() and Function.prototype.call() to invoke a function?

var func = function() {
  alert('hello!');
};

func.apply(); vs func.call();

Are there performance differences between the two aforementioned methods? When is it best to use call over apply and vice versa?

javascript function performance dynamic 
4 Answers

The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters to be listed explicitly. A useful mnemonic is "A for array and C for a comma."

See MDN's documentation on apply and call.

Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

theFunction.call(valueForThis, arg1, arg2, ...)

There is also, as of ES6, the possibility to spread the array for use with the call function, you can see the compatibilities here.

Sample code:

function theFunction(name, profession) {
    console.log("My name is " + name + " and I am a " + profession +".");
}
theFunction("John", "fireman");
theFunction.apply(undefined, ["Susan", "school teacher"]);
theFunction.call(undefined, "Claude", "mathematician");
theFunction.call(undefined, ...["Matthew", "physicist"]);

answered Jan 17


Here's a good mnemonic. Apply uses Arrays and Always takes one or two Arguments. When you use Call you have to Count the number of arguments.

answered Jan 17


call() Method: It calls the method, taking the owner object as an argument. The keyword this refers to the ‘owner’ of the function or the object it belongs to. We can call it a method that can be used on different objects.

Syntax:

object.objectMethod.call( objectInstance, arguments )

Parameters: It accepts two parameters as mentioned above and described below:

  • objectInstance: It holds the instance of an object.
  • arguments: The call() method takes the comma-separated arguments.

apply() Method: The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array.
Syntax:

object.objectMethod.apply(objectInstance, arrayOfArguments)

Parameters: It accepts two parameters as mentioned above and described below:

  • objectInstance: It holds the instance of an object.
  • arrayOfArguments: The apply() method takes the array of arguments.

Difference between call() and apply() method: The only difference is the call() method takes the arguments separated by a comma while apply() method takes the array of arguments.

answered Jan 17


Fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

answered Jan 17


Login and Submit Your Answer
Browse other questions tagged  javascript  function  performance  dynamic or ask your own question.