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 ofthis
provided for the call tofunc
.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()