Checks how many arguments a function takes in Javascript?

Javascript

Javascript Problem Overview


With arguments.length I can see how many arguments were passed into a function.

But is there a way to determine how many arguments a function can take so I know how many I should pass in?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Solution 3 - 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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionajsieView Question on Stackoverflow
Solution 1 - JavascriptHarmenView Answer on Stackoverflow
Solution 2 - JavascriptMatthew VinesView Answer on Stackoverflow
Solution 3 - JavascriptTOPKATView Answer on Stackoverflow