What is the use of apply() function in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Traditionally we have objects which have their own unique methods and properties. Using apply() function we can construct a method that can access all the given objects combined.

Actually, this method works the same as call() function but when there is a need to pass an array like variables, apply() function comes into the picture.

In the following example, multiple elements were called individually, so there is no need to use apply() function instead call() function is used.

Example

Live Demo

<html>
<body>
   <script>
      var obj = {num : 10};
      var mul = function(i, j, k){
         return this.num * i*j*k;
      }
      document.write(mul.call(obj,6,3,4));
   </script>
</body>
</html>

Output

720

In the following example instead of individual elements, when an array is passed then call() function has returned NaN whereas apply() function returned a value. This is because the call() function cannot access an array. 

Example

Live Demo

<html>
<body>
   <script>
      var obj = {num : 10};
      var mul = function(i, j, k){
         return this.num * i*j*k;
      }
      var array = [6,3,4]
      document.write(mul.call(obj,array));
      document.write("</br>");
      document.write(mul.apply(obj,array));
   </script>
</body>
</html>

Output

NaN
720
raja
Published on 01-Jul-2019 15:34:59
Advertisements