Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checks how many arguments a function takes in Javascript?

Tags:

javascript

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?

like image 440
ajsie Avatar asked Nov 09 '10 20:11

ajsie


People also ask

How can you determine the number of arguments passed to a JavaScript function?

length property provides the number of arguments actually passed to a function.

How many arguments does the function take?

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.

How many arguments can a function have JavaScript?

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.

How do you check if an argument is a function JavaScript?

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.


2 Answers

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.

like image 166
Harmen Avatar answered Sep 27 '22 19:09

Harmen


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.

like image 26
Matthew Vines Avatar answered Sep 27 '22 19:09

Matthew Vines