Use Variable Number of Arguments in JavaScript Function



To use a variable number of arguments to function, use the arguments object.

Example

You can try to run the following code to implement arguments to a function in JavaScript

Live Demo

<html>
   <body>
      <script>
         function functionArgument(val1, val2, val3)  {
            var res = "";
            res += "Expected Arguments: " + functionArgument.length;
            res += "<br />";
            res += "Current Arguments : " + arguments.length;

            res += "<br />";
            res += "Each argument = "

            for (p = 0; p < arguments.length; p++) {
               res += "<br />";
               res += functionArgument.arguments[p];
               res += " ";
            }
            document.write(res);
         }
         functionArgument(20, 50, 80, "Demo Text!","Hello World", new Date())
      </script>
   </body>
</html>
Updated on: 2020-01-07T09:37:34+05:30

599 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements