What is apply()?

fn.apply(thisArg, argsArray) calls a function immediately with this set to thisArg and its arguments taken from an array (or array-like object); it is call with an array instead of a list.

Classic uses

  • Passing an array as separate arguments before spread existed: Math.max.apply(null, numbers).
  • Forwarding arguments in wrappers: return fn.apply(this, arguments) keeps both the original this and every argument, which is how many debounce, memoize and logging helpers were written.
  • Borrowing methods for array-like objects.

apply vs spread

Since ES2015, Math.max(...numbers) and fn.call(ctx, ...args) replace most uses of apply and read better. apply is still handy when you have both a context and an existing array or arguments object to pass through.

Limit on argument count

Engines limit how many arguments a single call can receive (often around 65k to a few hundred thousand). Math.max.apply(null, hugeArray) or Math.max(...hugeArray) can throw a RangeError for very large arrays. Use reduce or a loop for those.

Reflect.apply

Reflect.apply(fn, thisArg, args) is the same operation as a standalone function. It is safer when fn might have its own property called apply, and it is commonly used inside Proxy traps.

Code example

js
1const numbers = [5, 1, 9, 3];
2
3console.log(Math.max.apply(null, numbers)); // 9 (classic)
4console.log(Math.max(...numbers)); // 9 (modern equivalent)
5
6function describe(city, country) {
7 return `${this.name} lives in ${city}, ${country}`;
8}
9const ada = { name: "Ada" };
10console.log(describe.apply(ada, ["London", "UK"])); // Ada lives in London, UK
11
12// Forwarding `this` and all arguments in a wrapper
13function logCalls(fn) {
14 return function (...args) {
15 console.log(`calling ${fn.name} with`, args);
16 return fn.apply(this, args);
17 };
18}
19const user = {
20 name: "Grace",
21 greet: logCalls(function greet(greeting) {
22 return `${greeting}, ${this.name}`;
23 }),
24};
25console.log(user.greet("Hello")); // calling greet with ["Hello"] -> Hello, Grace
26
27// Reflect.apply: same operation as a plain function
28console.log(Reflect.apply(Math.min, null, numbers)); // 1
29
30// Very large arrays: use reduce instead of spreading/apply
31const big = Array.from({ length: 200_000 }, (_, i) => i);
32console.log(big.reduce((max, n) => (n > max ? n : max), -Infinity)); // 199999

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app