In JavaScript, apply()
is a method that allows you to call a function with a specific this
context and arguments provided as an array. It’s particularly useful when you want to invoke a function with a dynamic number of arguments.
Contents
Example
function greet(greeting, punctuation) {
return `${greeting}, ${this.name}${punctuation}`;
}
const person = { name: 'Alice' };
console.log(greet.apply(person, ['Hello', '!'])); // "Hello, Alice!"
What it does
The apply()
method calls the greet
function, setting this
to the person
object and passing the arguments (‘Hello’, ‘!’) in an array. This is handy when you want to control the this
context in a function.
this
context: It changes thethis
reference inside the function to the object you provide (person
in this case).- Array of arguments: Unlike
call()
,apply()
takes an array as its second parameter, which is useful when you want to pass multiple arguments efficiently.
Examples
Example 1: Using apply()
to find the maximum value in an array
const numbers = [3, 5, 1, 8, 2];
const max = Math.max.apply(null, numbers);
console.log(max); // 8
Here, apply()
calls Math.max()
with null
as the this
context because Math.max()
doesn’t depend on this
. The array numbers
is passed as the arguments, allowing us to find the maximum value.
Example 2: Borrowing methods from one object to another
const car = {
brand: 'Toyota',
getDescription: function(speed) {
return `${this.brand} is driving at ${speed} km/h.`;
}
};
const bike = { brand: 'Yamaha' };
const result = car.getDescription.apply(bike, [120]);
console.log(result); // "Yamaha is driving at 120 km/h."
The apply()
method is used here to borrow the getDescription
method from the car
object and apply it to the bike
object. The this
inside getDescription
now refers to bike
, and 120
is passed as an argument.
Example 3: Using apply()
with built-in functions
const array = [1, 2, 3];
const newArray = Array.prototype.push.apply(array, [4, 5, 6]);
console.log(array); // [1, 2, 3, 4, 5, 6]
This example uses apply()
to call push
on array
, passing [4, 5, 6]
as elements to add. apply()
allows us to pass an array of elements directly into push
.
Example 4: Setting this
context for a function
function introduce(age) {
return `My name is ${this.name}, and I am ${age} years old.`;
}
const person = { name: 'Bob' };
console.log(introduce.apply(person, [25])); // "My name is Bob, and I am 25 years old."
Here, apply()
is used to set the this
context to the person
object, allowing the introduce
function to use person.name
. The age is passed as an argument in an array.