Javascript Function apply()

The JavaScript Function apply() method calls a function with a given this value, and arguments provided as an array.

The syntax of the apply() method is:

func.apply(thisArg, argsArray)

Here, func is a function.


apply() Parameters

The apply() method takes in:

  • thisArg - The value of this provided for the call to func.
  • argsArray (optional) - An Array-like object containing the arguments to the function.

Return value from apply()

  • Returns the result of calling the function with the specified this value and arguments.

By using apply(), we can use the built-in functions for some task that would have probably required looping over the array values otherwise.

Example: Using apply() with built-in functions

const numbers = [5, 1, 4, 3, 4, 6, 8];

let max = Math.max.apply(null, numbers);
console.log(max); // 8

// similar to
let max1 = Math.max(5, 1, 4, 3, 4, 6, 8);
console.log(max1); // 8

let letters = ["a", "b", "c"];
let other_letters = ["d", "e"];

// array implementation
for (letter of other_letters) {
  letters.push(letter);
}
console.log(letters); // [ 'a', 'b', 'c', 'd', 'e' ]

letters = ["a", "b", "c"];
// using apply()
letters.push.apply(letters, other_letters);
console.log(letters); // [ 'a', 'b', 'c', 'd', 'e' ]

Output

8
8
[ 'a', 'b', 'c', 'd', 'e' ]
[ 'a', 'b', 'c', 'd', 'e' ]

Recommended Reading: JavaScript Function call()