The arguments parameter
The arguments parameter is a collection of all the arguments passed to the function. The collection has a property named length
that contains the count of arguments, and the individual argument values can be obtained using an array indexing notation. Okay, we lied a bit. The arguments parameter is not a JavaScript array, and if you try to use array methods on arguments, you'll fail miserably. You can think of arguments as an array-like structure. This makes it possible to write functions that take an unspecified number of parameters. The following snippet shows you how you can pass a variable number of arguments to the function and iterate through them using an arguments array:
var sum = function () { var i, total = 0; for (i = 0; i < arguments.length; i += 1) { total += arguments[i]; } return total; }; console.log(sum(1,2,3,4,5,6,7,8,9)); // prints 45 console.log(sum(1,2,3,4,5)); // prints 15
As we discussed, the arguments parameter is not really an...