Skip to content

JavaScript function apply | Example code

  • by

JavaScript function apply invokes a function with a given this value and arguments provided as an array. The apply() method is similar to the call() method.

JavaScript apply function example

A simple example code gets the full name using the object.

<!DOCTYPE html>
<html>
<body>

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

  const person1 = {
    firstName: "Steve",
    lastName: "Mike"
  }


  var res = person.fullName.apply(person1);
  console.log(res)
</script>

</body>
</html> 

Output:

JavaScript function apply

The apply() Method with Arguments

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

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

  var res = person.fullName.apply(person1, ["big", "kin"]);

  console.log(res)
</script>

Output: John King,big,kin

Build-in Function.apply()

<script>
   const numbers = [5, 6, 2, 3, 7];

   const max = Math.max.apply(null, numbers);
   console.log(max);

   const min = Math.min.apply(null, numbers);
   console.log(min);
 </script>

Here’s another example that demonstrates how the apply() method can be used to pass an array of arguments to a function:

function multiplyNumbers(a, b) {
  return a * b;
}

const numbers = [3, 5];

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

Do comment if you have any doubts or suggestions on this JS apply() method.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading