2

Below are apply and call functions:

function.apply(context, [args])

function.call(context, arg1, arg2, ...)

We know the difference between apply and call:

The difference is that apply lets you invoke the function with arguments as an array; call requires the parameters be listed explicitly.

Now we have spread syntax, we can easily use call to do what apply does:

function.call(context, ...[args])

So with spread syntax, when do we use apply over call? I am curious if apply function can be retired.

6324
  • 3,610
  • 4
  • 26
  • 58
  • 1
    Apply still makes sense if you're building function pipelines in a functional programming style. Read up on point free programming if you'd like to learn more. – tex Sep 29 '17 at 17:35

1 Answers1

4

Considering that args is array-like iterable, it is

function.call(context, ...args);
// vs
function.apply(context, args);

And apply is shorter.

apply is native and thus faster than call with spread arguments. The difference can vary between browser versions and be negligible (recent Chrome/V8) or drastic (Firefox, older Chrome/V8). Depending on the case, this concern may be considered preliminary optimization.

The results can differ between browser versions, depending on the existence of optimizations for spread syntax and arguments. Previously array-like arguments could kill optimization in apply, notably in V8. This is no longer a problem in modern engines that support spread syntax.

Practical difference appears if arguments are array-like but not iterable. For instance, arguments became iterable not so long ago, ...arguments will fail in older browser versions even if they support spread syntax. So apply is preferable here, because call would need a safety device:

function.call(context, ...Array.from(arguments));
// vs
function.apply(context, arguments);

On the other hand, there is practical difference if arguments are iterable but not array-like, too. Since apply accepts array-likes, call will be preferable and likely faster:

function.call(context, ...set);
// vs
function.apply(context, [...set]);
Estus Flask
  • 150,909
  • 47
  • 291
  • 441