JavaScript apply() Method
Subject: JavaScript
The apply() method in JavaScript invokes a function with a given this value, similar to call(), but takes the arguments as an array or array-like object. It is useful when arguments are already in array form.
Syntax
- functionName: The function to call.
 - thisArg: The value of this inside the function.
 - [arg1, arg2, ...]: An array of arguments passed to the function.
 
Example 1: Basic Use of apply()
Example 2: Reuse Methods from Another Object
Example 3: Math Functions with apply()
Use apply() to pass an array to functions expecting individual arguments.
Note: Math.max does not accept arrays directly; apply() spreads the array elements as arguments.
Difference Between call() and apply()
- call() passes arguments one by one.
 - apply() passes arguments as an array.
 
Example 4: Function Reusability with apply()
Key Takeaways
- apply() calls a function with a specific this and arguments as an array.
 - Useful when arguments are in array form or dynamic.
 - Works similarly to call() but with a different argument format.
 - Commonly used with functions like Math.max, Math.min, etc.