The apply() Method
You'll learn how to invoke a function with a custom this value and pass arguments as an array.
What Is apply()?
The apply() method lets you call a function while explicitly setting what this refers to inside that function. It works just like call(), but with one key difference: instead of passing arguments individually, you pass them as an array (or array-like object).
The syntax looks like this:
functionName.apply(thisValue, [arg1, arg2, arg3]);
The first parameter is what this should be, and the second is an array containing all the arguments.
Why Use apply()?
Sometimes you have arguments stored in an array and need to pass them to a function. Instead of manually spreading them out, apply() handles it for you.
Example:
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
const args = ['Hello', '!'];
greet.apply(person, args); // "Hello, Alice!"
Here, this.name becomes 'Alice' because we passed person as the first argument. The array args provides the two parameters greeting and punctuation.
apply() vs call()
Both methods set this explicitly. The only difference:
- call() takes arguments individually:
func.call(thisValue, arg1, arg2) - apply() takes arguments as an array:
func.apply(thisValue, [arg1, arg2])
Use apply() when your arguments are already in array form.
Key Takeaway: The apply() method invokes a function with an explicit this value and accepts arguments as an array, making it ideal when your parameters are already collected together.