Checks how many arguments a function takes in Javascript?
Edge cases
Beware, before counting on fn.length
, there are some edge cases where the result may not be what you expect:
const fn1 = ( a, b ) => {}; // length: 2
const fn2 = ( a = 0, b ) => {}; // length: 0
const fn3 = ( ...params ) => {};// length: 0
const fn4 = ( a, b = 1, c ) => {};// length: 1
fn.length
doesn't seem to recognize default values or rest operator.
You can mess with this codePen
The arity
property specifies the number of arguments the current function expected to receive. This is different to arguments.length
which indicates how many actual arguments were passed in.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/arity
Edit
Note that arity
has been deprecated since v1.4. The correct way to get the number of arguments expected is now function.length
as suggested by Harmen.
Function.length
will do the job (really weird, in my opinion)
function test( a, b, c ){}
alert( test.length ); // 3
By the way, this length property is quite useful, take a look at these slides of John Resig's tutorial on Javascript
EDIT
This method will only work if you have no default value set for the arguments.
function foo(a, b, c){};
console.log(foo.length); // 3
function bar(a = '', b = 0, c = false){};
console.log(bar.length); // 0
The .length
property will give you the count of arguments that require to be set, not the count of arguments a function has.