8

Possible Duplicate:
Get a function’s arity

How can I declare a function expression, pass it into a defined function, and have the defined function determine how many arguments the function expression has?

See this code snippet for reference:

function getArgumentCount(fexp)
{
    return ...;
}

var fexp1 = function(a) { };
var fexp2 = function(a, b) { };

console.log(getArgumentCount(fexp1)); // Should output 1
console.log(getArgumentCount(fexp2)); // Should output 2
Community
  • 1
  • 1
Phil K
  • 4,939
  • 6
  • 31
  • 56
  • You may well be able to do something by processing the output of `func.toString()`. Counting the commas before the first `)` in the string would probably do it. – Jim Blackler Dec 02 '12 at 21:40
  • something along the lines of: function myFunc(){for(i in arguments){switch(typeof(arguments[i])){case ....}}} – technosaurus Dec 02 '12 at 21:56

2 Answers2

18

javascript functions have a .length property

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/length

Alex
  • 1,077
  • 6
  • 7
2

You can do this by using theFunction.length, but I would advise against this: among other reasons:

  • It won't work on functions bound with naïve Function.bind shims.
  • It won't work on native functions. (e.g. window.open)1

1 On Chrome, at least; it seems to work in Firefox.

icktoofay
  • 126,289
  • 21
  • 250
  • 231