Loop through parameters passed to a Javascript functionLoop through parameters passed to a Javascript function

Posted November 27th, 2009 in Javascript

I looked at how to set default values for parameters in a Javascript function the other day and in this post look at the arguments object which can be used to work out how many parameters were passed to a function and also to loop through each of them.

The arguments object in functions

The arguments object is a special property available within Javascript functions and behaves like an array. It has a length property and can be looped through like a regular array.

To check how many arguments or parameters were passed to a function check the length property. The following example simply writes out into the document the number of parameters passed:

function foo() {
    document.write(arguments.length + "<br />");
}

To test:

foo();
foo('apples');
foo('apples', 'bananas');
foo('apples', 'bananas', 'oranges');

And the output:

0
1
2
3

You could therefore do something based on the number of arguments passed to the function:

function foo() {
    if(arguments.length == 0) {
        // do something
    }
    else {
        // do something else
    }
}

Looping through the parameters

Looping through the arguments is just like looping through a regular array:

function foo() {
    for (var i = 0, j = arguments.length; i < j; i++){
        document.write(arguments[i]+' ');
    }
    document.write('<br />');
}

Using the same test as the earlier example above, the output would be:


apples
apples bananas 
apples bananas oranges

Related posts:

Comments

blog comments powered by Disqus