JavaScript | Function Apply
The apply() method is used to write methods, which can be used on different objects. It is different from the function call() because it takes arguments as an array.
Syntax:
apply()
Return Value: It returns the method values of a given function.
Example 1: This example illustrates the apply() function without arguments.
<!DOCTYPE html> <html> <head> <title> JavaScript apply() Method without argument </title> </head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript apply() Method </h2> <h4> It displays the details of second student </h4> <p id="GFG"></p> <!-- Script to use apply() method --> <script> var student = { details: function() { return this.name + "<br>" + this.class; } } var stud1 = { name:"Dinesh", class: "11th", } var stud2 = { name:"Vaibhav", class: "11th", } var x = student.details.apply(stud2); document.getElementById("GFG").innerHTML = x; </script> </body> </html> |
Output:

Example 2: This example illustrates the apply() function with arguments.
<!DOCTYPE html> <html> <head> <title> JavaScript apply() Method with argument </title> </head> <body> <h1>GeeksforGeeks</h1> <h2> JavaScript apply() Method </h2> <h4> It displays the details of second student </h4> <p id="GFG"></p> <!-- Script to use apply() method --> <script> var student = { details: function(section, rollnum) { return this.name + "<br>" + this.class + " " + section + "<br>" + rollnum; } } var stud1 = { name:"Dinesh", class: "11th", } var stud2 = { name:"Vaibhav", class: "11th", } var x = student.details.apply(stud2, ["A", "24"]); document.getElementById("GFG").innerHTML = x; </script> </body> </html> |
Output:

Recommended Posts:
- What is the difference between call and apply in JavaScript?
- PHP | Ds\Deque apply() Function
- PHP | Ds\Vector apply() Function
- PHP | Ds\Sequence apply() Function
- Apply function to every row in a Pandas DataFrame
- How to apply !important in CSS?
- Kotlin | apply vs with
- Difference between map, applymap and apply methods in Pandas
- How to call a function that return another function in JavaScript ?
- JavaScript | Symbol.for() function
- JavaScript | Function Parameters
- JavaScript | Function Invocation
- JavaScript | Array.of() function
- JavaScript | Math.pow( ) Function
- JavaScript | Function Definitions
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



