What is the difference between using Function.prototype.apply() and Function.prototype.call() to invoke a function?
const func = function() {
alert("Hello world!");
};
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?
The difference is that
applylets you invoke the function withargumentsas an array;callrequires the parameters be listed explicitly. A useful mnemonic is "A for array and C for comma."See MDN’s documentation on apply and call.
Pseudo syntax:
theFunction.apply(valueForThis, arrayOfArgs)theFunction.call(valueForThis, arg1, arg2, ...)There is also, as of ES6, the possibility to
spreadthe array for use with thecallfunction, you can see the compatibilities here.Sample code: