0 votes
1 view
in Web Technology by (47.8k points)

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

var func = function() { 



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 (107k 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"]); 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !