In Javascript, how can one determine the number of formal parameters defined for a function?
Note, this is not the arguments
parameter when the function is called, but the number of named arguments the function was defined with.
function zero() {
// Should return 0
}
function one(x) {
// Should return 1
}
function two(x, y) {
// Should return 2
}
A function arity is the number of parameters the function contains.It can be attained by calling the length property.
inspect.getargspec(func) returns a tuple with four items, args, varargs, varkw, defaults : len(args) is the "primary arity", but arity can be anything from that to infinity if you have varargs and/or varkw not None , and some arguments may be omitted (and defaulted) if defaults is not None .
Arity (/ˈærɪti/ ( listen)) is the number of arguments or operands taken by a function, operation or relation in logic, mathematics, and computer science. In mathematics, arity may also be named rank, but this word can have many other meanings in mathematics.
Fixed arity function is the most popular kind present in almos tall programming languages. Fixed arity function must be called with the same number of arguments as the number of parameters specified in its declaration. Definite arity function must be called with a finite number of arguments.
> zero.length
0
> one.length
1
> two.length
2
Source
A function can determine its own arity (length) like this:
// For IE, and ES5 strict mode (named function)
function foo(x, y, z) {
return foo.length; // Will return 3
}
// Otherwise
function bar(x, y) {
return arguments.callee.length; // Will return 2
}
As is covered in other answers, the length
property tells you that. So zero.length
will be 0, one.length
will be 1, and two.length
will be 2.
As of ES2015, we have two wrinkles:
arguments
pseudo-array)The "rest" parameter isn't counted when determining the arity of the function:
function stillOne(a, ...rest) { }
console.log(stillOne.length); // 1
Similarly, a parameter with a default argument doesn't add to the arity, and in fact prevents any others following it from adding to it even if they don't have explicit defaults (they're assumed to have a silent default of undefined
):
function oneAgain(a, b = 42) { }
console.log(oneAgain.length); // 1
function oneYetAgain(a, b = 42, c) { }
console.log(oneYetAgain.length); // 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With