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 pattern | Modern 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', '!']);
Five letters.
Discussion
Loading…