What is the difference between call and apply?

Explanation

The difference between call and apply is that apply will allow you to invoke the function with arguments as an array. Whereas the call will require the parameters that can be listed explicitly. 

See MDN’s documentation on apply and call.

Pseudo syntax:

theFunction.apply(valueForThis, arrayOfArgs)

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

Here we have a 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");
theFunction.call(undefined, ...["Matthew", "physicist"]); // used with the spread operator

 

Also read, What is the !! (not not) operator in JavaScript?

Share this post

Leave a Reply

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