3

For instance, say I have

var numbers = [5, 6, 2, 3, 7];

var max = Math.max.apply(null, numbers);

console.log(max);

or,

var numbers = [5, 6, 2, 3, 7];

var max = Math.max.call(null, ...numbers);

console.log(max);

Why would I choose call or apply over something similar to the below?

var numbers = [5, 6, 2, 3, 7];

var max = Math.max(...numbers);

console.log(max);

I've been able to get away with coding in Javascript without using either of these two methods (or bind) but I'd like to know if I should start using them.

Mike K
  • 7,621
  • 14
  • 60
  • 120
  • Use it when you need to set the calling context (the `this`) inside the called function. It's often not so useful anymore since we have arrow functions and parameter spread syntax – CertainPerformance Aug 02 '19 at 12:05
  • The first one using `apply()` would work in ES5 environments where spread operator not supported. No benefit using first two over last one when `thisArg` is null and spread supported – charlietfl Aug 02 '19 at 12:07
  • @CertainPerformance ...or when you want to curry. As a silly off-the-top-of-my-head example, `foo[i].addEventListener('click', handleClick.bind(this, i))`... – Amadan Aug 02 '19 at 12:10
  • One of the uses of `call` is to convert an array-like item to array: `[].slice.call()` – adiga Aug 02 '19 at 12:15
  • IMHO not precisely a duplicate. Keep in mind that if you don't need to set the `this` value, there's no reason to use `call` or `apply`, you can use the spread syntax right in the call expression. Using `call` with the spread syntax: `someFunction.call(obj, ...args);` doesn't make sense, you can use `apply` and pass the array of arguments directly. – Christian C. Salvadó Aug 02 '19 at 12:15

0 Answers0