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

30 / Jan / 2013 by Suroor Wijdan 1 comments

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:

[js]
(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); [/js]

Using apply() method:

[js] (function sum(a,b) {
var i, k=0;
var num = arguments.length;
for (i = 0; iNode 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.

FOUND THIS USEFUL? SHARE IT

comments (1 “Difference between call() and apply() method of JavaScript”)

Leave a Reply

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