Reputation: 136
I have run across code that invokes a function as fn(a,b,c) but the definition of fn is fn(a,b) and then inside the author invokes arguments[2] which would imply a third undeclared argument. Is this legit? (I am new to the site and tried to search for a related question before posting, but was unable to find one. If there is a custom for doing so, I would love to be educated.) Thanks.
Upvotes: 2
Views: 771
Reputation: 16468
It's allowed. It's usually better to specify good argument names and then check if they are null or not, for readability and sanity. People reading your code won't expect or understand that technique.
There are cases where it acceptable... for example:
function add(){
var sum = 0;
for (var i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
However, even in this case it would be better to add placeholder variable names for the sake of readers:
function add(val1, val2, etc){
var sum = 0;
for (var i = 0; i < arguments.length; i++){
sum += arguments[i];
}
return sum;
}
Upvotes: 6
Reputation: 5050
Its ugly, BUT is also used in many javascript frameworks, such as jQuery. There are obvious advantages to using it for some purposes, but I'd follow these general rules:
Upvotes: 1
Reputation: 90493
It's legal, but I would avoid it as a matter of style. It's usually a better idea to declare the argument - by doing so, you make the meaning of the function more obvious. One can just look at the function name and argument list to (hopefully) get an idea of the function's purpose.
I'd reserve usage of the arguments
array for completely variable-length argument lists, not just a single optional parameter.
Upvotes: 0
Reputation: 3757
Another alternative might be to pass an array as a single argument and iterate over its contents or an object (name value pairs) passing arguments of interest and ignoring others. I prefer to pass an object.
Upvotes: 0