Get arity function

In Javascript, how to determine the number of formal parameters defined for a function?

Note that this is not the arguments parameter when calling the function, but the number of named arguments with which the function was defined.

 function zero() { // Should return 0 } function one(x) { // Should return 1 } function two(x, y) { // Should return 2 } 
+49
javascript functional-programming arity
Jan 31 '11 at 6:21
source share
5 answers
 > zero.length 0 > one.length 1 > two.length 2 

Source

A function can define its own arity (length) as follows:

 // 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 } 
+54
Jan 31 '11 at 6:25
source share

The arity function is stored in the .length property.

 function zero() { return arguments.callee.length; } function one(x) { return arguments.callee.length; } function two(x, y) { return arguments.callee.length; } > console.log("zero="+zero() + " one="+one() + " two="+two()) zero=0 one=1 two=2 
+11
Jan 31 '11 at 6:25
source share

As described in other answers, the length property reports this. So zero.length will be 0, one.length will be 1, and two.length will be 2.

As in ES2015, we have two wrinkles:

  • Functions can have a β€œrest” parameter at the end of the parameter list, which collects any arguments given at or after this position into a real array (as opposed to the arguments pseudo-array)
  • Function parameters may have default values.

The "rest" parameter is not taken into account when determining the arity of a function:

 function stillOne(a, ...rest) { } console.log(stillOne.length); // 1 

Similarly, a parameter with a default argument does not add to arity and actually prevents any others following it from adding to it, even if they do not have explicit default values ​​(it is assumed that they have a default value of undefined ):

 function oneAgain(a, b = 42) { } console.log(oneAgain.length); // 1 function oneYetAgain(a, b = 42, c) { } console.log(oneYetAgain.length); // 1 
+4
Dec 15 '16 at 18:57
source share

The arity of a function is the number of parameters that the function contains. It can be achieved by calling the length property.

Example:

 function add(num1,num2){} console.log(add.length); // --> 2 function add(num1,num2,num3){} console.log(add.length); // --> 3 

Note: the number of parameters passed in the function call does not affect the functionality.

0
Oct 26 '17 at 6:17
source share

The arity property used to return the number of arguments expected by the function, however, it no longer exists and is replaced by the Function.prototype.length property.

0
Dec 18 '17 at 2:39 on
source share



All Articles