Function Apply in JavaScript
?? Function.prototype.apply() in JavaScript
What is apply()?
apply()is a method available on all JavaScript functions.It calls a function with a given
thisvalue, and arguments provided as an array (or array-like object).Useful when you want to control the
thiscontext and pass arguments dynamically.
Syntax
func.apply(thisArg, [argsArray])thisArg: The value to use asthisinside the function.argsArray: An array or array-like object of arguments to pass to the function.
Example 1: Basic Usage
function greet(greeting, punctuation) { console.log(greeting + ", " + this.name + punctuation);}const person = { name: "Alice" };// Call greet with 'person' as this and arguments in an arraygreet.apply(person, ["Hello", "!"]); // Output: Hello, Alice!Example 2: Using apply to Find Max in an Array
const numbers = [5, 6, 2, 9, 1];// Math.max expects separate arguments, not an arrayconst max = Math.max.apply(null, numbers);console.log(max); // 9Difference Between apply() and call()
Both set the
thiscontext.call()accepts arguments one by one.apply()accepts arguments as an array.
func.call(thisArg, arg1, arg2, ...);func.apply(thisArg, [arg1, arg2, ...]);Why Use apply()?
When the number of arguments is unknown or already in an array.
When you want to reuse functions with different contexts dynamically.
Summary
| Aspect | apply() |
|---|---|
| Calls a function | Yes |
Sets this | Yes |
| Arguments | As an array or array-like object |
Want me to show you how to implement your own version of apply() or how to use it with constructor functions?