JavaScript Reference ยท Function
Function.prototype.apply()
Reference for JavaScript Function.prototype.apply(): call a function with a chosen this and an array of arguments, and when spread syntax is better.
apply() calls a function immediately, with an explicit this and with the arguments supplied as a single array (or array-like object). It is identical to call() except for how arguments are passed.
Before spread syntax existed, apply() was the standard way to pass an array as separate arguments, as in Math.max.apply(null, numbers). It still has a place when you forward an arguments object or an array-like.
fn.apply(thisArg, [arg1, arg2]);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
fn.apply(thisArg) fn.apply(thisArg, argsArray)
| Name | Description |
|---|---|
thisArg |
The value to use as this inside the call. |
argsArray |
Optional. An array or array-like object (anything with length and indexed items) whose items become the arguments. null or undefined means no arguments. |
Return value: whatever the function returns.
Exceptions: a TypeError if argsArray is not an object, array-like, null or undefined, or if apply is used on a non-function.
Usage notes
- Spread replaces most uses.
fn.call(ctx, ...args)andMath.max(...numbers)are easier to read and also accept any iterable. - Array-likes work. Unlike spread,
apply()accepts{ length: 2, 0: "a", 1: "b" }and theargumentsobject without converting them first. - Size limits. Every item becomes a stack argument, and engines cap how many are allowed. Applying to arrays with hundreds of thousands of items can throw a
RangeError. Loop or reduce instead. - Empty array pitfalls.
Math.max.apply(null, [])returns-Infinity, just likeMath.max(). - Same
thisrules ascall(): strict mode usesthisArgas is, sloppy mode substitutes the global object fornullorundefined, and arrow functions ignore it. - Forwarding wrappers (decorators, memoizers, loggers) typically use
fn.apply(this, arguments)orfn.apply(this, args)to pass everything through unchanged.
Browser support
apply() is available in every browser and JavaScript runtime.