apply() method in JavaScript | Example code

  • by

The apply() method calls a function with a given value, and arguments are provided as an array in JavaScript. The apply() method calls a function by passing this value and arguments provided as an array.

func.apply(thisArg, argsArray)

The apply() method is similar to the call() method but call() method takes arguments separately and apply() method takes arguments as an array.

Example apply method in JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>

  <script>
    // object definition 
    const pName = {
      fname: 'John',
      lname: 'Steve'
    }

    //  function definition  
    function greet(wish, message) {
      return `${this.fname}, ${wish}. ${message}`;
    }

    // using apply() method 
    let result = greet.apply(pName,['Good morning', 'How are you?']);

    console.log(result);
  </script>

</body>
</html> 

Output:

apply() method in JavaScript

Append two arrays

let color1= ["Red", "Green", "Blue"];
let color2= ["Yellow", "Black"];


color1.push.apply(color1,color2);

console.log(color1);

Output: [ ‘Red’, ‘Green’, ‘Blue’, ‘Yellow’, ‘Black’ ]

The apply() Method with Arguments

<script>
    const person = {
      fullName: function(city, country) {
        return this.firstName + " " + this.lastName + ", " + city + ", " + country;
      }
    }

    const person1 = {
      firstName:"John",
      lastName: "Doe"
    }

    var res = person.fullName.apply(person1, ["Oslo", "Norway"]);
    console.log(res)
</script>

Output: John Doe, Oslo, Norway

Do comment if you have any doubts or suggestions on this JS basic method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.