apply() Function in JavaScript
The apply() method in JavaScript is used to invoke a function with a specified this value and arguments provided as an array (or array-like object). This is useful when you want to call a function with a specific context or when the arguments are unknown or dynamic.
Key Points about apply() Function:
- The apply() method allows a function to be called with a given this value and an array of arguments.
- It is often used when you have an array of values that you want to pass as arguments to a function.
- Syntax: function.apply(thisArg, [argsArray]).
- The this context inside the function will refer to the object provided as thisArg.
- If no arguments are provided, the argsArray can be set to null or undefined.
- Difference from call(): Unlike call(), which takes a list of arguments, apply() takes an array or array-like object.
apply() Syntax
function greet(name, age) {
console.log('Hello, ' + name + '. You are ' + age + ' years old.');
}
greet.apply(null, ['Alice', 25]);
Example of Using apply() Function in JavaScript:
This example demonstrates the usage of the apply()
method to call the greet()
function with a dynamic set of arguments passed in an array.
apply() Syntax
function greet(name, age) {
console.log('Hello, ' + name + '. You are ' + age + ' years old.');
}
greet.apply(null, ['Alice', 25]);
Output
Hello, Alice. You are 25 years old.
Using apply() with Different Contexts Syntax
Syntax
const person = {
name: 'Bob',
greet: function(age) {
console.log('Hello, ' + this.name + '. You are ' + age + ' years old.');
}
};
person.greet.apply({ name: 'Alice' }, [30]);
Example of Using apply()
with Different Contexts:
This example shows how the apply()
method can be used to call the greet()
method of the person
object with a different this
context.
Example
const person = {
name: 'Bob',
greet: function(age) {
console.log('Hello, ' + this.name + '. You are ' + age + ' years old.');
}
};
person.greet.apply({ name: 'Alice' }, [30]);
Output
Hello, Alice. You are 30 years old.