Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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 aforementioned methods? When is it best to use call over apply and vice versa?

1 Answer

0 votes
by (106k points)

The difference between call and apply is as follows:-

When you use apply it lets you invoke the function with arguments as an array; and when you use call it requires the parameters to be listed explicitly. 

Syntax for the apply and call is as follows:-

theFunction.apply(valueForThis, arrayOfArgs)

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

You can see the example code below:

function theFunction(name, profession) { 

console.log("My name is " + name + " and I am a " + profession +"."); 

theFunction("Hari", "driver"); 

theFunction.apply(undefined, ["rahul", "engineer"]); theFunction.call(undefined, "joe", "doctor"); theFunction.call(undefined, ...["ravi", "chemist"]); 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...