JavaScript apply() Method: A Complete Tutorial with Examples

The apply() method in JavaScript is used to call a function with a given this value and an array (or array-like object) of arguments.

It's similar to the call() method, but while call() passes arguments individually, apply() takes an array of arguments.

Basic Syntax of apply()

functionName.apply(thisArg, [argsArray])

thisArg: The value of this to be used inside the function.
argsArray: An array or array-like object containing arguments to be passed to the function.

1. Basic Usage of apply()

The apply() method allows you to invoke a function while explicitly setting its this context and passing arguments as an array.

Example 1: Using apply() to Call a Function

function greet(greeting, name) {
  console.log(`${greeting}, ${name}!`);
}

greet.apply(null, ['Hello', 'Alice']); // Output: Hello, Alice!

Explanation

The greet function takes two arguments: greeting and name.
apply(null, [‘Hello', ‘Alice']) sets this to null (indicating that this is not used inside the function) and passes [‘Hello', ‘Alice'] as arguments.

2. Using apply() to Set this Context

One of the most common use cases of apply() is to set the this context when invoking a method.

Example 2: Using apply() to Borrow a Method

let person1 = {
  name: 'Alice',
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

let person2 = {
  name: 'Bob'
};

// Borrow the greet method from person1 and use it for person2
person1.greet.apply(person2); // Output: Hello, my name is Bob

Explanation

person1 has a greet method that uses this.name.
Using apply(person2), we borrow person1.greet and set this to person2, allowing person2 to use person1's method.

3. Using apply() with Built-in Functions

The apply() method is particularly useful with built-in functions like Math.max() and Math.min(), which do not natively accept arrays as arguments.

Example 3: Finding the Maximum Value in an Array

let numbers = [3, 5, 1, 8, 2];
let max = Math.max.apply(null, numbers);

console.log(max); // Output: 8

Explanation

Math.max() takes a list of numbers as arguments.
apply(null, numbers) allows us to pass the numbers array to Math.max() by expanding the array elements as arguments.

4. Using apply() for Array-Like Objects

You can use apply() to convert array-like objects (e.g., the arguments object inside a function) into arrays.

Example 4: Converting arguments to an Array

function sum() {
  let argsArray = Array.prototype.slice.apply(arguments);
  return argsArray.reduce((acc, current) => acc + current, 0);
}

console.log(sum(1, 2, 3, 4, 5)); // Output: 15

Explanation

arguments is an array-like object containing all the arguments passed to the function.
Array.prototype.slice.apply(arguments) converts the arguments object into a true array.
The reduce() method is then used to sum the array elements.

5. Applying apply() for Maximum and Minimum Values in an Array

The apply() method can also be used to find the minimum value in an array using Math.min().

Example 5: Finding the Minimum Value in an Array

let numbers = [3, 5, 1, 8, 2];
let min = Math.min.apply(null, numbers);

console.log(min); // Output: 1

Explanation

Math.min() is used to find the minimum number in a list.
apply(null, numbers) passes the numbers array as individual arguments to Math.min().

6. Differences Between apply(), call(), and bind()

apply(thisArg, [argsArray]): Invokes the function with this set to thisArg and arguments provided as an array.
call(thisArg, arg1, arg2, …): Invokes the function with this set to thisArg and arguments provided individually.
bind(thisArg, arg1, arg2, …): Returns a new function with this set to thisArg and optionally preset arguments. It does not immediately invoke the function.

Example 6: Comparing apply(), call(), and bind()

function introduce(greeting, punctuation) {
  console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}

let person = {
  name: 'Charlie'
};

// Using apply
introduce.apply(person, ['Hello', '!']); // Output: Hello, my name is Charlie!

// Using call
introduce.call(person, 'Hi', '?'); // Output: Hi, my name is Charlie?

// Using bind
let boundIntroduce = introduce.bind(person, 'Hey');
boundIntroduce('!'); // Output: Hey, my name is Charlie!

Explanation

apply(): Passes arguments as an array.
call(): Passes arguments individually.
bind(): Creates a new function with a bound this and optional arguments.

7. Using apply() with Array-Like Objects (DOM NodeList)

You can use apply() to convert array-like objects such as a NodeList into an array to use array methods.

Example 7: Converting a NodeList to an Array

    <ul id="myList">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    </ul>
    
    <script>
    let listItems = document.querySelectorAll('#myList li');
    
    // Convert NodeList to an array using apply
    let listItemsArray = Array.prototype.slice.apply(listItems);
    
    // Now we can use array methods like forEach
    listItemsArray.forEach(item => {
    console.log(item.textContent);
    });
    </script>

    Output

    Item 1
    Item 2
    Item 3
    

    Explanation

    document.querySelectorAll() returns a NodeList, which is an array-like object.
    Array.prototype.slice.apply(listItems) converts the NodeList into a true array, allowing us to use array methods like forEach().

    8. Using apply() for Function Borrowing

    apply() can be used to borrow functions from one object and use them with another.

    Example 8: Borrowing Array Methods

    let arrayLikeObject = {
      0: 'apple',
      1: 'banana',
      2: 'cherry',
      length: 3
    };
    
    let result = Array.prototype.join.apply(arrayLikeObject, [', ']);
    console.log(result); // Output: apple, banana, cherry
    

    Explanation

    arrayLikeObject simulates an array with length and indexed properties.
    We use apply() to borrow the Array.prototype.join() method and apply it to arrayLikeObject.

    Summary

    The apply() method is a versatile tool in JavaScript for calling functions with a specified this context and passing arguments as an array. Here’s a quick recap of its key aspects:

    Key Points

    apply(): Calls a function with a specified this value and an array (or array-like object) of arguments.

    Use Cases:

    Borrowing methods from one object for use with another.
    Applying functions to arrays (Math.max(), Math.min(), etc.).
    Converting array-like objects (e.g., arguments, NodeList) into arrays.
    Difference from call(): apply() accepts arguments as an array, while call() requires them to be passed individually.
    Difference from bind(): apply() and call() invoke the function immediately, while bind() returns a new function.

    By mastering apply(), you gain more control over function execution, particularly in situations where you need to specify the this context and work with dynamic sets of arguments.

    Related posts

    JavaScript Callbacks: A Complete Tutorial

    JavaScript Arrow Functions: A Complete Tutorial

    JavaScript call() Method: A Complete Tutorial with Examples