DCSIMG
JavaScript tip: How to send unknown number of arguments to a function - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

JavaScript tip: How to send unknown number of arguments to a function

During my last lecture in the course: "Advanced JavaScript" I was asked by a student an interesting question. The question was, How do I create a function that can receive an unknown number of arguments. The hand was raised when we learned the Array construction function options. When you create an Array in JavaScript you have many option of creating it:
<script>
       var
arr = new Array(); //Creates an empty array.
      
var arrObj = Array(); //Creates an empty array.
      
var arr = new Array("One", "Two", "Three");
       var arrObj = Array(54, 32, 77, 76);
       var arr = new Array(5);    //Can you guess what will be the length of this array ? :-)

       var arrObj = Array(5);
   </script>

Notice the second and third options. This constructor function accepts an unknown of argument that will initialize the array and determine it's initial size.

OK, So what if we wish to create our own function that can get an unknown number if args? just like C# has params option.

Well the answer is very simple. Every JavaScript function is an object. This object has properties (From it's prototype). One of these properties is "arguments". The arguments property consists of an array of all the arguments passed to a function.

Here is a simple example of how to create a method named "Add" that can receive an unknown number of args:

<script>
      function Add()
      {
        var nSum = 0
        for (var i = 0; i < arguments.length; i++) {
            nSum = nSum + arguments[i]
        }
        return nSum;
    }
</script>
Enjoy!

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: