Difference between .call and .apply

      When one is reviewing the different methods available in Javascript they will inevitably come across the methods .call and .apply. They will also come across the following definitions from Mozilla Developer network:

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

      .apply() = The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

      Now for someone who’s just getting started these two definitions look extremely similar and it is incredibly hard to understand the difference between the two of them, but before we get to that first let’s take a look at what at what they actually do that’s so similar. The purpose of both call and apply is to call a function or method while assigning to it a different “this” object. This way you can call the function on another object without having to rewrite that function into that object.

      But if both of these functions are calling a function while providing a different assigning to it a different “this” object then why do we need two of them? The difference lies in the way in which the arguments are passed to the function. While .call expects these arguments to be provided individually .apply expects them to be provided as an array. Let’s look at an example .call:

var newObj = {
  objName: "Paulo"
};

var newFunction = function(animal1, animal2, animal3){
  console.log(this.objName + " has the following animals: " + animal1 + ", " + animal2 + ", " + animal3);
};

newFunction.call(newObj, 'dog', 'cat', 'bird');

newFunction.call is being called with the arguments ‘dog’, ‘cat’, and ‘bird’ passed in individually.

      Here is an example of the same function being use with .apply:

var newObj = {
  objName: "Paulo"
};

var newFunction = function(animal1, animal2, animal3){
  console.log(this.objName + " has the following animals: " + animal1 + ", " + animal2 + ", " + animal3);
};

var animalArray = ['dog', 'cat', 'bird'];

newFunction.apply(newObj, animalArray);

Now we are no longer passing in these values individually but as an array.

      In summary, both methods are being used to provide a new value for the “this” object in which your method/function is being called in. However, the .call method expects you to provide the arguments that the function takes individually, the .apply method expects those arguments to be passed in as an array.

Paulo Diniz