Function.prototype.apply
Calls a function with a given this and an array of arguments.
Available since: ES3
Syntax
fn.apply(thisArg, argsArray)Parameters
| Parameter | Type | Description |
|---|---|---|
| thisArg | any | The this value for the call. |
| argsArray | Array | An array of arguments. |
Return value
anyThe function's result.
Examples
Arguments as an array:
function introduce(greeting, punctuation) {
return `${greeting}, I am ${this.name}${punctuation}`;
}
console.log(introduce.apply({ name: 'Anna' }, ['Hi', '!']));Output:
Hi, I am Anna!This used to find an array maximum; now spread does it:
const numbers = [3, 9, 4];
console.log(Math.max.apply(null, numbers));
console.log(Math.max(...numbers));Output:
9
9Notes
In modern code apply() is almost entirely replaced by spread: fn(...args) or fn.call(thisArg, ...args).
See also
- Function.prototype.call — Calls a function with a given this and arguments.
- Function.prototype.bind — Creates a copy of a function with a fixed this and, optionally, arguments.
- Spread syntax — Three dots spread an array or object into separate items.
In the tutorial
- this, call, apply and bind — How this is determined in JavaScript, why a method loses its context, and how to set this by hand with call, apply and bind.