08/09/2011

JavaScript Functions With an Undefined Number of Arguments

In JavaScript there is an easy way to retrieve all the arguments that were passed to the function even if we do not know how many were passed. There is an arguments array-LIKE object. Notice it is not an array, but similar to one. We cannot join(), pop(), push(), slice(), etc. like we can with an array, but we can retrieve the values from the object like we do an array.

Example
<script type="text/javascript">
function sum() {
    var total = 0;
    for (var i = 0, len = arguments.length; i < len; ++i) {
        total += arguments[i];
    }
    return total;
}
 
sum(1, 2, 3, 4) // returns 10
 
</script>

Leave a Reply

Your email address will not be published. Required fields are marked *



user-avatar
Today is Sunday
03/26/2017