Flexible Arguments

Contact Us or call 1-877-932-8228
Flexible Arguments

Flexible Arguments

JavaScript offers us a way to handle cases where we don't know in advance how many arguments are to be passed to a function. Consider a function which returns an HTML unordered list from a set of strings. We could declare our function to accept an array parameter, loop over the array inside the function to build the unordered list, and return the formatted HTML - but this would require any calling code to first build an array of strings to pass to the function:

var arr = ['item 1', 'item 2', 'item 3'];
document.write(formatAsList(arr));

which would not be as useful as a function that accepts the elements as parameters:

document.write(formatAsList('item 1', 'item 2', 'item 3'));

Of course, we would want the function to accept any arbitrary number of parameters:

document.write(formatAsList('item 1'));
document.write(formatAsList('item 1', 'item 2', 'item 3', 'item 4', 'item 5'));
// etc.

We can't enumerate the parameters in our function definition, even if we used default values for the parameters, because we don't know in advance how many parameters will be passed in the call to our function. Instead, we use the arguments object.

The arguments object is a local variable available within any function. It contains an entry for all of the arguments passed to the function, regardless of whether the function has a formal parameter in its declaration for the passed parameter(s).

A function declared as

function foo(bar) {
	return arguments[1] + ' ' + arguments[2];
}

and called as

document.write(foo('a','b','c'));

would print to the screen the value 'b c', since the arguments object would have three elements ('a', 'b', and 'c') with indices 0, 1, and 2, respectively. Inside function foo, the value of parameter bar and the value of arguments[0] would both be 'a'.

While the arguments object is not an array, we can convert it into an array using Array's from method:

function argsFun1(bar) {
	var myargs = Array.from(arguments);
}
//...
argsFun1('a', 'b', 'c');

or, if we want only a portion of the arguments collection, using Array's slice method:

function argsFun2(bar) {
	var myargs = Array.from(arguments).slice(1);
}
//...
argsFun2('a', 'b', 'c');

In the first example above, the call to argsFun1 would result in the local variable myargs being set to a three-element array with elements 'a', 'b', and 'c' - that is, an Array of all of the passed-in arguments. In the second example above, the call to argsFun2 would set its myargs variable to an Array with two elements, 'b' and 'c', since the slice method returns us the "slice" of the array starting at (and including) the element with index 1.

Thus the following code:

function argsFun1(bar) {
	var myargs = Array.from(arguments);
	console.log('argsFun1: ' + myargs);
}

function argsFun2(bar) {
	var myargs = Array.from(arguments).slice(1);
	console.log('argsFun2: ' + myargs);
}

argsFun1('a', 'b', 'c');
argsFun2('a', 'b', 'c');

would print the following to the console:

argsFun1: a,b,c
argsFun2: b,c

Let's look at an example:

Code Sample:

AdvancedFunctions/Demos/argumentsObject.html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>The arguments Object</title>
</head>
<body>
	<h1>The arguments Object</h1>
	<script>
		function formatAsList(listType) {
			var myargs = Array.from(arguments).slice(1);
			if (myargs.length == 0) {
				return '';
			}
			$html_str = '<' + listType + '>';
			for (var i in myargs) {
				$html_str += '<li>' + myargs[i] + '</li>';
			}
			$html_str += '</' + listType + '>';
			return $html_str;
		}

		document.write(formatAsList('ul','item 1','item 2','item 3'));
		document.write('<hr>');
		document.write(formatAsList('ul'));
		document.write('<hr>');
		document.write(formatAsList('ol','red','green','blue','orange'));
	</script>
</body>
</html>

Code Explanation

Function formatAsList has one formally declared parameter, listType, which expects to receive a value ul (for an unordered list) or ol (for an ordered list).

Function formatAsList first converts its arguments object to an Array (myargs) using the slice method, getting all of the elements except the first (0th) element. If the length of myargs is 0, then the function returns the empty string. If not - that is, if there is at least one parameter to be formatted as an HTML list - then the function builds an HTML string for a list of the specified (ul or ol) type, iterating over the array to build the list items.

The screenshot below shows the output we would get from running the code above:

screenshot of arguments object demo

The first call to formatAsList, on line 23, returns an unordered list with three elements: "item1", "item2", and "item3".

The second call to formatAsList, on line 25, returns the empty string, since there is only one parameter supplied ('ul') and, thus, Array.from(arguments).slice(1) has length zero.

The third call to formatAsList, on line 27, returns an ordered list with four items - the color names.

Next