iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Function apply()

Function.prototype.apply(thisArg, argsArray) is identical to call except the arguments come as an array.

Quick comparison

JS
function greet(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const user = { name: "Ada" };

greet.call (user, "Hi", "!");          // "Hi, Ada!"
greet.apply(user, ["Hi", "!"]);        // "Hi, Ada!"

Classic apply use cases (and modern equivalents)

Old apply patternModern equivalent
Math.max.apply(null, arr)Math.max(...arr)
fn.apply(this, arguments)fn(...args) with rest params
arr.push.apply(arr, items)arr.push(...items)
new (Date.bind.apply(Date, [null, ...args]))()new Date(...args) via Reflect.construct

The one case where apply still wins

When you have a function reference and an arguments-like object you can't easily spread (e.g. from inside a Proxy trap or Reflect.apply):

JS
const proxy = new Proxy(target, {
  apply(fn, thisArg, args) {
    log("called with", args);
    return Reflect.apply(fn, thisArg, args);   // forwards everything
  },
});
Tip: In day-to-day code, prefer spread (...). It reads better and works in places apply can't, like constructor calls.

Example

Example
<!DOCTYPE html>
<html>
<body>

<p id="out"></p>

<script>
document.getElementById("out").textContent = "Hello from Function apply()!";
</script>

</body>
</html>
Try it Yourself »

Exercise

Invoke greet with `user` as `this` and the args as an array.

greet. (user, ['Hi', '!']);

Test yourself

Q1. `apply` takes the args as…
Q2. In modern code, prefer apply or spread?
Q3. Reflect.apply(fn, thisArg, args) returns…

Discussion

Loading…