Know How Many Parameters are Received by the Function
by Mohan[ Edit ] 2012-09-20 22:26:26
Know How Many Parameters are Received by the Function Using arguments Object
This technique lets you know how many parameters are received by the function using “arguments” object. For example:
function add_nums(){
return arguments.length;
}
add_nums(23,11,32,56,89,89,89,44,6); //this return the number 9
This is very useful at the time you need to check the number of parameter in validations or even to create a function with undetermined parameters.
function sum_three_nums( ){
if(arguments.length!=3) throw new Error('received ' + arguments.length + ' parameters and should work with 3');
}
sum_three_nums(23,43); //Return the error message
function sum_num(){
var total = 0;
for(var i=0;i
total+=arguments[i];
}
return total;
}
sum_num(2,34,45,56,56);