The apply() method is a built-in JavaScript function method that allows you to call a function with a specific this context and arguments passed as an array.

It is very similar to call(), but arguments are provided in an array instead of individually.

1.Syntax

functionName.apply(thisArg, [argsArray])
  • functionName → the function you want to invoke
  • thisArg → the value of this inside the function
  • [argsArray] → an array (or array-like object) containing arguments

2.Basic Example

function greet(greeting, punctuation) {
console.log(`${greeting}, my name is ${this.name}${punctuation}`);
}
const user = { name: "Zaman" };

greet.apply(user, ["Hello", "!"]); // Hello, my name is Zaman! 

this inside greet is now user object
✔ Arguments are passed as an array

3.Borrowing Methods From Other Objects

const person1 = {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
};
const person2 = { firstName: "Ahmed", lastName: "Khan" };

console.log(person1.fullName.apply(person2)); // Ahmed Khan

✔ Useful to reuse methods across objects

4.Using apply() With Math Functions

apply() is often used with functions that take variable number of arguments, like Math.max:

const numbers = [5, 6, 2, 3];

const max = Math.max.apply(null, numbers);
console.log(max); // 6

const min = Math.min.apply(null, numbers);
console.log(min); // 2

null is used for this because Math functions don’t rely on this

Categorized in:

Javascript,