JavaScript Function apply()
14 April 2025 | Category: JavaScript
In JavaScript, the apply()
method is used to call a function with a given this
value and arguments provided as an array (or array-like object).
It works similarly to the call()
method, but with one key difference: how the arguments are passed.
✅ Syntax
functionName.apply(thisArg, [arg1, arg2, ...])
Parameters:
thisArg
: The value ofthis
inside the function.[arg1, arg2, ...]
: An array of arguments.
🔍 Example: Using apply()
to Set this
function introduce(language) {
console.log(`I'm ${this.name}, and I speak ${language}.`);
}
const person = { name: "Amit" };
introduce.apply(person, ["Hindi"]);
// Output: I'm Amit, and I speak Hindi.
💡 introduce
is not a method of person
, but apply()
sets this
to person
.
🔁 Difference: call()
vs apply()
Feature | call() | apply() |
---|---|---|
Arguments | Passed individually | Passed as an array |
Example | func.call(thisArg, a, b) | func.apply(thisArg, [a, b]) |
🧠 Real-life Use Case: Math.max()
const numbers = [4, 7, 2, 9];
const max = Math.max.apply(null, numbers);
console.log(max); // Output: 9
You can’t pass an array directly to
Math.max()
, butapply()
allows you to spread the array as arguments.
🧬 Function Borrowing with apply()
const person1 = { fullName: "Alice Cooper" };
const person2 = { fullName: "Bob Marley" };
function sayHello(greeting) {
console.log(`${greeting}, I'm ${this.fullName}`);
}
sayHello.apply(person2, ["Hey"]);
// Output: Hey, I'm Bob Marley
🔄 apply()
+ arguments
Object
Sometimes used to forward arguments dynamically:
function sum() {
return Array.prototype.reduce.apply(arguments, [(acc, curr) => acc + curr]);
}
console.log(sum(1, 2, 3, 4)); // 10
⚠️ Notes
- In strict mode, if
null
orundefined
is passed asthisArg
, it stays asnull
orundefined
. - In non-strict mode,
null
orundefined
defaults to the global object (window
in browsers).
🧾 Summary
apply()
is great for calling functions with array-based arguments.- It gives you control over the
this
value and lets you dynamically pass arguments. - Perfect for scenarios like borrowing functions or spreading arrays as arguments.