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?
length property provides the number of arguments actually passed to a function.
Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.
When you call a function in JavaScript, you can pass in any number of arguments, regardless of what the function declaration specifies. There is no function parameter limit.
Use the typeof operator to check if a function is defined, e.g. typeof myFunction === 'function' . The typeof operator returns a string that indicates the type of a value. If the function is not defined, the typeof operator returns "undefined" and doesn't throw an error.
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.
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
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.
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