• support@answerspoint.com

What is the difference between call and apply?

2075

What is the difference between using call and apply to invoke a function?

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

func.apply();

vs

func.call();

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

2Answer


0

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

See MDN's documentation on apply and call.

Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

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

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");
  • answered 8 years ago
  • Sunny Solu

0

  

Many people get confused with these two functions in JavaScript, most of the time people think that we can pass an object in apply() and access it with this which is not possible with the call() method. But that is not the case, let’s see an example which will make it more clear.

Using call() method:

 
 
 
 
 
 
 
 
 
 
 
 
 
 
(function sum(a,b,c) {
 var i, k=0;
 var num = arguments.length;
 for (i = 0; i < num; i++) {
 k+= arguments[i];
 }
 console.log(this.toString()); //prints body of the function passed i.e., test()
 console.log(k); //prints the sum in console
 this(); // this will call the test() function passed to sum
 return k; //returns sum
 
}).call(function test() {
 console.log(10); //prints 10 in console
 },10,100);

Using apply() method:

 
 
 
 
 
 
 
 
 
 
 
 
 
 
(function sum(a,b) {
    var i, k=0;
    var num = arguments.length;
    for (i = 0; i<num; i++) {
        k+= arguments[i];
    }
    console.log(this.toString()); //prints body of the function passed i.e., test()
    console.log(k);               //prints the sum in console
    this();             // this will call the test() function passed to sum
    return k;           //returns sum
 
}).apply(function test() {
       console.log(10); //prints 10 in console
    },[10,100,200,200]);

Try it online at Node Console

So the basic difference between both the methods is that in call() method we have to pass comma separated arguments and in apply() method we have to pass an array. If you have any queries then do let me know in comments section below.

  

  • answered 8 years ago
  • G John

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 2075 times
  • active 9 years ago

Best Rated Questions