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.
views:
64answers:
5It'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;
}
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.
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.
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:
- don't use it simply because some (known) arguments are optional. Instead, name the arguments (or take an object as an argument instead) and check the arguments (or object's properties) explicitly for null or undefined
- if the method is something that could potentially take an unknown/infinite number of arguments, it would make sense to use this approach, for example if you were for some reason creating a custom concat() method, you might want to allow any number of arguments
- if you do use it, comment any parts of the code that may be confusing to follow, in particular, you'd want to comment/document how the function should be called