Functions: Number of Arguments is Actually Ignored

by Lucille Kenney

HTML

<b><p>Number of arguments is actualy ignored.</p>Open your console to see the output from this code!</b>
<p>Notice the new Array variable <code>arguments</code> that's available inside  any function. It contains all of the arguments passed in the function call, in order. </p>
<p>We can call this function and pass any number of arguments, even if there are no parameters in the function definition itself. We iterate over the <code>arguments</code> array, check each element to see if it is or can be converted to a number, and then add it to our sum. </p>

JavaScript

/* This function will add as many numbers as are passed in.
 * Note the new Array variable that's available inside 
 * any function. It contains all of the arguments passed
 * in the function call, in order.
 */ 
function addNumbers(){
    var sum=0;		
    console.log("number of arguments: "+arguments.length);
    for (var i=0; i<arguments.length;i++){
		if (Number(arguments[i])){
			sum+=arguments[i]; 
		}
    }
	return sum;
}
console.log("The sum is " + addNumbers(1, 2, 3, 4, 5, "dog"));