How to Use apply() Method in JavaScript: Simple Guide
In JavaScript,
apply() is a method used to call a function with a given this value and arguments provided as an array or array-like object. It allows you to control the context of this inside the function and pass arguments dynamically.Syntax
The apply() method is called on a function and takes two arguments:
- thisArg: The value to use as
thisinside the function. - argsArray: An array or array-like object containing arguments to pass to the function.
It looks like this:
javascript
functionName.apply(thisArg, argsArray);
Example
This example shows how to use apply() to call a function with a specific this value and arguments passed as an array.
javascript
const person = { fullName: function(city, country) { return this.firstName + ' ' + this.lastName + ', ' + city + ', ' + country; } }; const person1 = { firstName: 'John', lastName: 'Doe' }; const result = person.fullName.apply(person1, ['New York', 'USA']); console.log(result);
Output
John Doe, New York, USA
Common Pitfalls
Common mistakes when using apply() include:
- Passing arguments as separate values instead of an array.
- Using
nullorundefinedasthisArgunintentionally, which defaultsthisto the global object orundefinedin strict mode. - Confusing
apply()withcall(), which takes arguments separately, not as an array.
Here is an example showing the wrong and right way:
javascript
// Wrong: arguments not in an array function greet(greeting, punctuation) { console.log(greeting + ', ' + this.name + punctuation); } const obj = { name: 'Alice' }; // greet.apply(obj, 'Hello', '!'); // This causes an error // Right: arguments passed as an array greet.apply(obj, ['Hello', '!']); // Output: Hello, Alice!
Output
Hello, Alice!
Quick Reference
| Part | Description |
|---|---|
| functionName.apply(thisArg, argsArray) | Calls function with specified this and arguments as array |
| thisArg | Object to use as this inside the function |
| argsArray | Array or array-like object of arguments to pass |
| Returns | Result of the function call |
Key Takeaways
Use apply() to call a function with a specific this value and arguments as an array.
The first argument sets the this context inside the function.
The second argument must be an array or array-like object of parameters.
apply() differs from call() by accepting arguments as an array.
Avoid passing arguments separately or using null/undefined unintentionally as thisArg.