Skip to content
Related Articles

Related Articles

JavaScript | Function Apply
  • Last Updated : 12 Mar, 2019

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:




My Personal Notes arrow_drop_up
Recommended Articles
Page :