Categories:

The arguments array- the secret to robust functions

The arguments array is a secretive little object that exists inside every function. As you effortlessly pass in parameters into a function, the arguments array is working hard not only storing the values of these parameters into one of its array element, but jotting down the total number of parameters passed as well. This is realized through the following syntax:

functionname.arguments.length="contains the total number of parameters"
functionname.arguments[0]="contains the value of the first parameter in the function"
functionname.arguments[1]="contains the value of the second parameter in the function"
"
"

Note: The functionname proceeding the arguments array is optional.

You're baffled, and I don't blame you. The best way to understand this object is to see it at work, so lets do just that. The below's a function that accepts three parameters. Lets use the arguments array to expose that, and more!

function mynumbers(firstword, secondword, thirdword){
	alert("Total # of parameters="+mynumbers.arguments.length)
	for (i=0;i<arguments.length;i++)
		alert(mynumbers.arguments[i])
}

The above's a basic function that accepts three parameters. Lets call it now, and see what the arguments array has to offer:

<script>
//call the function
mynumbers("How","are","you")
</script>

What's the big deal with this example, you say. Plenty! Sure, its obvious from simply looking at the function what the total number of parameters is, and the values of each parameter, but we never could tell by using JavaScript codes. Now, we could, through the arguments array of a function.

Creating robust functions

With the help of the arguments array, in addition to a minor change when defining a function, we can create a function that accepts any number of parameters.

The first order of buisness is to define a robust function. A function as such looks exactly the same as a function with say, two or three parameters, only that the parameters are not explicitly specified.

function robust(){

}

Now that that's out of the way, the remaining work is to create a mechanism using the arguments array that dynamically retrieves all of the parameters that get passed in, so the remaining portion of the function can do its job with them. A simple for loop will do nicely:

function robust(){
for (i=0;i<robust.arguments.length;i++)
	//do whatever
}