What is the difference between using call
and apply
to invoke a function?
var func = function() {
alert(\'hello!\');
};
>
Let me add a little detail to this.
these two calls are almost equivalent:
func.call(context, ...args); // pass an array as list with spread operator
func.apply(context, args); // is same as using apply
There’s only a minor difference:
- The
spread
operator ... allows passing iterableargs
as the list to call.- The
apply
accepts only array-like args.
So, these calls complement each other. Where we expect an iterable, call
works, where we expect an array-like, apply
works.
And for objects that are both iterable and array-like, like a real array, we technically could use any of them, but apply will probably be faster because most JavaScript engines internally optimize it better.