• JavaScript Video Tutorials

JavaScript Handler apply() Method



In JavaScript, the handler.apply() method lets you call a function with particular arguments and context (works like a trap to the function call). It is used to invoke a function, but it also allows an array of arguments to be specified in addition to this value. This is particularly useful in situations where you want to call a function with a specific object as the context or when you have an array of arguments that you want to pass to the function. This method is similar to the call() method, but instead of passing a individual arguments, we can pass an array of arguments.

Syntax

Following is the syntax of JavaScript handler.apply() method −

new Proxy(target, {
   apply(target, thisArg, argumentsList) {}
});

Parameters

  • target − It holds the target object.
  • thisArg − The this argument for the call.
  • argumentsList − It contains the list of arguments for the call.

Return value

This method returns can return any value.

Example 1

Let's look at the following example, where we are going to use the array containing the arguments to be passed to the add function, and then we use apply() to invoke the function.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
function add(a, b) {
   return a + b;
}
const x = [22, 11];
const y = add.apply(null, x);
document.write(y);
</script>
</body>
</html>

Example 2

Consider another scenario where we are going to call a function in a different context.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
const x = {
   car: 'Audi Q6',
   greet: function() {
      return 'Ford ' + this.car;
   }
};
const y = {
   car: 'Mustang'
};
const a = x.greet.apply(y);
document.write(a);
</script>
</body>
</html>

Example 3

In the following example, we are going to pass all the elements of the array as individual arguments to the function.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
function sum() {
   const x = Array.from(arguments);
   return x.reduce((acc, val) => acc + val, 0);
}
const y = [10, 20, 30, 40, 50];
const result = sum.apply(null, y);
document.write(result);
</script>
</body>
</html>

When we execute the above script, the output window will pop up, displaying the sum on the webpage.

Example 4

Following is the example, where we are going to find the max value in the array by calling Math.max with the array as the argument.

<html>
<style>
body {
   font-family: verdana;
   color: #DE3163;
}
</style>
<body>
<script>
   const x = [11, 222, 3, 412];
   const result = Math.max.apply(null, x);
   document.write(result);
</script>
</body>
</html>

On executing the above script, the output window will pop up displaying the max number in the array on the webpage.

Advertisements