Skip to content

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

The apply() method is often used in conjunction with the arguments object to pass a variable number of arguments to a function. For example:

function sum() {
  let total = 0;
  for (let i = 0; i < arguments.length; i++) {
    total += arguments[i];
  }
  return total;
}

const numbers = [1, 2, 3, 4, 5];

const result = sum.apply(null, numbers);
console.log(result); // Output: 15

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

Leave a Reply

Your email address will not be published. Required fields are marked *