Table of Contents

Introduction

JavaScript apply() method calls a function with a specified this value and arguments supplied as an array or array-like object. It is useful when the arguments are already stored in a collection and you want to pass them to a function individually. By controlling the function context and how arguments are supplied, apply() helps reuse functions across different objects and work with dynamic argument lists.

JavaScript apply() Method Syntax

The apply() method is available on JavaScript functions through Function.prototype. Its syntax is:

functionName.apply(thisArg, argsArray);
  • thisArg: The value to use as this when the function executes. It can be an object, primitive value, null, or undefined.
  • argsArray: An array or array-like object containing the arguments that should be passed to the function. If no arguments are needed, you can pass null or undefined.

The function runs immediately when apply() is called. The method returns whatever value the original function returns.

How the apply() Method Works

When you call a function with apply(), JavaScript performs two important operations. First, it sets the function’s this value to the value provided as the first argument. Second, it takes the values from the second argument and passes them to the function as separate positional arguments.

For example, an array containing ["Mina", 25] is not passed as one argument. Instead, the function receives "Mina" as its first parameter and 25 as its second parameter.

function introduce(name, age) {
  return `My name is ${name} and I am ${age} years old.`;
}

const details = ["Mina", 25];

console.log(introduce.apply(null, details));
// My name is Mina and I am 25 years old.

In this example, the function does not use this, so null is supplied for the context. The array values are passed as individual arguments.

Using apply() to Set the this Value

The first argument of apply() determines the value of this inside a regular function. This is useful when a function needs to operate on different objects without being permanently attached to any one of them.

function showProfile() {
  return `${this.name} works as a ${this.role}.`;
}

const employee = {
  name: "Rahim",
  role: "Developer"
};

const manager = {
  name: "Nadia",
  role: "Project Manager"
};

console.log(showProfile.apply(employee));
// Rahim works as a Developer.

console.log(showProfile.apply(manager));
// Nadia works as a Project Manager.

The same showProfile() function is reused for both objects. The value of this changes according to the object passed to apply(). No duplicate function definitions are required.

Passing an Array of Arguments with apply()

One of the main reasons to use apply() is to pass an existing array as a function’s argument list. This is especially useful when the number of arguments is determined at runtime or when values are collected from a form, API response, or another data source.

function calculateTotal(price, quantity, discount) {
  return price * quantity - discount;
}

const orderValues = [500, 3, 100];

const total = calculateTotal.apply(null, orderValues);

console.log(total); // 1400

Here, apply() passes the three array elements as the three parameters expected by calculateTotal(). You do not need to access each array element manually.

Using apply() with Array-Like Objects

The second argument of apply() does not have to be a real array. It can be an array-like object: an object with a non-negative integer length property and indexed values. For example, the arguments object inside a traditional function is array-like, even though it is not an actual array.

function showArguments() {
  function display(first, second, third) {
    console.log(first, second, third);
  }

  display.apply(null, arguments);
}

showArguments("HTML", "CSS", "JavaScript");
// HTML CSS JavaScript

The outer function receives three arguments. Its arguments object is passed to display() through apply(), which forwards the indexed values as separate parameters. In modern code, rest parameters are often clearer when defining a function that accepts a variable number of arguments.

Using apply() to Find the Maximum Value in an Array

The global Math.max() function accepts individual numeric arguments, not an array directly. You can use apply() to provide the elements of an array as those arguments.

const numbers = [12, 45, 8, 67, 23];

const maximum = Math.max.apply(null, numbers);

console.log(maximum); // 67

Similarly, Math.min() can find the smallest value:

const minimum = Math.min.apply(null, numbers);

console.log(minimum); // 8

This technique was widely used before the spread syntax became common. For very large arrays, avoid passing an extremely large number of arguments at once because JavaScript engines may impose argument-count limits. A loop or a reduction is more suitable for large collections.

Using apply() to Reuse Object Methods

You can borrow a method from one object and execute it with another object as its context. This technique is known as method borrowing. It can be helpful when multiple objects need the same behavior but do not share a prototype or class.

const person = {
  fullName: function(city, country) {
    return `${this.firstName} ${this.lastName} from ${city}, ${country}`;
  }
};

const user = {
  firstName: "Sadia",
  lastName: "Akter"
};

const result = person.fullName.apply(user, ["Dhaka", "Bangladesh"]);

console.log(result);
// Sadia Akter from Dhaka, Bangladesh

The fullName() method belongs to person, but it is executed with user as this. The city and country are supplied as an array and passed as separate arguments.

Using apply() with an Empty Argument List

If a function does not require parameters, pass null or undefined as the second argument. The first argument still determines the intended this value.

function getName() {
  return this.name;
}

const customer = {
  name: "Karim"
};

console.log(getName.apply(customer, null));
// Karim

In this example, getName() receives no parameters, but its this value is set to customer.

apply() and Strict Mode

The behavior of this can differ depending on whether the called function is in strict mode. In a non-strict regular function, a null or undefined thisArg is replaced with the global object. In strict mode, the supplied value is preserved, so this remains null or undefined.

"use strict";

function showThis() {
  return this;
}

console.log(showThis.apply(null, []));
// null

When a primitive value such as a number or string is supplied as thisArg, strict-mode functions receive that primitive value as-is. Non-strict functions may convert it to an object wrapper. Understanding this distinction helps when a function relies on its execution context.

Difference Between call(), apply(), and bind()

The methods call(), apply(), and bind() all let you control the this value of a function, but they handle execution and arguments differently.

Method Argument format When function executes Return value
call() Arguments are passed individually. Immediately. The function’s result.
apply() Arguments are supplied as an array or array-like object. Immediately. The function’s result.
bind() Arguments can be supplied individually and partially preset. When the returned function is called. A new bound function.

Consider the following example:

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

const user = { name: "Ayesha" };

console.log(greet.call(user, "Hello", "!"));
// Hello, Ayesha!

console.log(greet.apply(user, ["Hello", "!"]));
// Hello, Ayesha!

const boundGreet = greet.bind(user, "Hello");
console.log(boundGreet("!"));
// Hello, Ayesha!

Choose call() when arguments are already separate, apply() when they are grouped in an array-like collection, and bind() when you need a reusable function with a fixed context. In modern JavaScript, spread syntax can often replace apply() when you already have an iterable array.

Using Spread Syntax as an Alternative to apply()

ES6 introduced the spread syntax (...), which expands an iterable such as an array into individual function arguments. For many everyday tasks, it provides a shorter and more readable alternative to apply().

const scores = [72, 88, 95, 61];

const maximumWithApply = Math.max.apply(null, scores);
const maximumWithSpread = Math.max(...scores);

console.log(maximumWithApply);  // 95
console.log(maximumWithSpread); // 95

Both expressions pass the array values as separate arguments. Spread syntax is generally preferred in modern JavaScript when the argument source is an iterable. However, apply() remains useful when working with array-like objects that are not iterable, and it is important to recognize in existing JavaScript code.

Important Details About the apply() Return Value

The apply() method does not create a new function. It executes the target function immediately and returns the exact value produced by that function. If the target function returns a number, string, object, or another value, apply() returns that value. If the target function has no explicit return statement, the result is undefined.

function multiply(a, b) {
  return a * b;
}

const result = multiply.apply(null, [6, 7]);

console.log(result); // 42

If the target function throws an error, the error is propagated to the code that called apply(). The method does not automatically catch exceptions or convert the function into an asynchronous operation.