What is the difference between call and apply in JavaScript?

JavascriptWeb DevelopmentFront End Technology

In JavaScript, .call and .apply are considered a method of function object.

.call method

Count the number of arguments with call method. It accepts one or more arguments as objects.

Here’s the syntax:

.call(object, “argument1”, “argument2”);

.apply method 

To use an array as an argument, use .apply. It requires an array as its 2nd argument.

Here’s the syntax:

.apply(object, [“argument1”, “argument[]”]);

Example

Let’s see an example showing both call and apply method:

<!DOCTYPE html>
<html>
   <head>
      <body>
         <script>
            var p = {
               q: "Hello"
            }
            function showResult(v) {
               document.write(this.q + " " + v);
            }
            showResult.call(p, "Amit"); // one or more objects as argument
            showResult.apply(p, ["World"]); // array as the second argument
         </script>
      </body>
   </head>
</html>
raja
Published on 09-Jan-2018 13:28:43
Advertisements