Philipp Burckhardt

On Statistics, Programming and the Social Sciences

Arbitrary Function Arguments in JavaScript

One interesting aspect of functions as implemented in JavaScript is that they allow for an arbitrary number of arguments. When a function is called, it will be passed an arguments object, which is an Array-like construct that contains all arguments passed to the function which can be then accessed like an Array: arguments[0] returns the first argument, and arguments[arguments.length - 1] the last one. Although arguments has a length attribute, it is not an Array and misses many of the useful methods ordinary Arrays inherit from Array.prototype in JavaScript.

There is not a real reason for this, it is just one of the many quirks in the language. To alleviate this problem, we can use Array.prototype.slice.call( arguments ) to turn it into a real array.

Let us consider a practical example: We will construct a function which takes any number of numeric arguments and returns as a result the sum of all these:

function sumAll() {
   var args = Array.prototype.slice.call( arguments );
   var total = 0;
   args.forEach( function( element ) {
     total += element;
   });
   return total;
};

As one can see, we do not explicitly define any function parameters. However, we can still call the function and pass it arguments, which will be then contained in arguments, which we turn into an Array in the second line. We initialize the sum of all the elements as zero and then iterate over the elements of the newly created args array and increment the total variable by the value of the selected element. Notice that we were able to use the forEach method because args is a real array: arguments.forEach on the other hand does not exist.

We now have a function which can add as many numbers as we would like. Calling sumAll( 3, 4, 2, 1 ) would return 10, and sumAll( 1, 1 ) gives us back 2.