Function Arity and JavaScript
A commenter on my last post asked about variable arity methods in JavaScript. Arity, for those unfamiliar with that term, simply refers to the number of parameters a function takes. In dynamic languages, however, arity is a more, well, dynamic concept, since a function can often be called with any number of parameters, or even with a collection to be taken as the argument list. So there are actually two different things going on, which I'll call invocation arity and declaration arity.
There's not much to invocation arity in JavaScript; you've probably seen it hundreds of times before. To determine the arity of invocation from within a method, just use the
length property of the array-like arguments object:SomeType.prototype.foo = function () {
if (arguments.length > 2) {
// do something requiring > 2 arguments
}
}
Declaration arity is similar: I can ask for the
length property of the function itself. So for example, if I was passed a function into some higher-order operation, I might check the function's arity to determine how to invoke it:function foreach(array, callback) {
for (var i = 0; i < array.length; ++i) {
if (callback.length === 1) {
// yield the element
callback(array[i]);
} else {
// yield the index and the element
callback(i, array[i]);
}
}
}
Beware declaration arity though: if your function is trying to be smart about its own arity by foregoing formal parameters and just using its
arguments object, it will advertise its arity as zero:function sum() {
var s = 0;
for (var i = 0; i < arguments.length; ++i) {
s += arguments[i];
}
return s;
}
print(sum.length); // prints 0
Labels: javascript

