β
1. What Is apply()
?
The apply()
method allows you to invoke a function, while explicitly specifying:
- The
this
context - The arguments (as an array or array-like object)
jsCopyEditfunction sayHello() {
console.log("Hello, " + this.name);
}
const user = { name: "Alice" };
sayHello.apply(user); // Hello, Alice
π 2. Syntax
jsCopyEditfunc.apply(thisArg, [arg1, arg2, ...])
func
: the function to be calledthisArg
: the value to use asthis
when the function runs[]
: an array of arguments
π 3. Example: Passing Arguments with apply()
jsCopyEditfunction introduce(language1, language2) {
console.log(`${this.name} speaks ${language1} and ${language2}`);
}
const person = { name: "Bob" };
introduce.apply(person, ["English", "French"]);
// Output: Bob speaks English and French
π 4. Difference Between call()
and apply()
Feature | call() | apply() |
---|---|---|
Arguments | Passed individually | Passed as an array |
Use case | When arguments are known | When arguments are in array |
Example:
jsCopyEditfunc.call(thisArg, arg1, arg2);
func.apply(thisArg, [arg1, arg2]);
π 5. Use Case: Math.max with Arrays
You canβt pass an array directly to Math.max
, but you can use apply()
:
jsCopyEditconst nums = [10, 30, 5, 8];
const max = Math.max.apply(null, nums);
console.log(max); // 30
β Works because
apply()
spreads the array into individual arguments.
π 6. Use Case: Borrowing Methods
jsCopyEditconst arrayLike = {
0: "a",
1: "b",
length: 2
};
// Borrow Array method
const realArray = Array.prototype.slice.apply(arrayLike);
console.log(realArray); // ["a", "b"]
π 7. ES6 Replacement: Spread Operator
In modern JavaScript, the spread syntax often replaces apply()
:
jsCopyEditMath.max(...[10, 20, 30]); // 30
But apply()
is still useful in older environments and for method borrowing.
π§ͺ Practice Tasks
- Create a function
greetUser(greeting)
and useapply()
to pass{ name: "Sam" }
and["Good morning"]
. - Use
Math.min.apply()
to find the smallest number in[3, 8, -5, 12]
.
π§ Summary
Feature | Description |
---|---|
func.apply() | Calls a function with this and arguments (as an array) |
Best for | Arrays, array-like objects, dynamic arguments |
Alternative | Use spread ... in modern JavaScript |
Would you like:
- π PDF or print-friendly version?
- π» Live playground (e.g., CodePen or JSFiddle)?
- π§ Short quiz or flashcards?