Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
fn.apply(thisArg, [arg1, arg2]);

Try it

JS Arguments from an array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Forwarding and array-likes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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) and Math.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 the arguments object 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 like Math.max().
  • Same this rules as call(): strict mode uses thisArg as is, sloppy mode substitutes the global object for null or undefined, and arrow functions ignore it.
  • Forwarding wrappers (decorators, memoizers, loggers) typically use fn.apply(this, arguments) or fn.apply(this, args) to pass everything through unchanged.

Browser support

apply() is available in every browser and JavaScript runtime.