April 9, 2020
Estimated Post Reading Time ~

Difference between call() and apply() method of JavaScript

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(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 the apply() method we have to pass an array.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.