0
(function (a, b, c) {

  console.log(arguments.length); // 2

} (1, 2) )

When the above function runs, the function can tell it was called with only two arguments via the arguments object's length property.

Is there also a way for the function to tell that it was expecting 3 arguments since a, b, & c are listed in the definition of the function?

In the above function:

console.log( what?) === 3?

I read through this answer Get a function's arity but it requires a reference (such as a name) to the function and does not answer my question with respect to the console.log being inside the function.

Community
  • 1
  • 1
ciso
  • 2,887
  • 6
  • 33
  • 58
  • 1
    Actually I did find [Finding the number of function parameters in JavaScript](http://stackoverflow.com/q/6293214/1048572) which was closed as a dupe of that. However, I did know the term "arity" and it would've been my next try after [this](https://stackoverflow.com/search?q=number+of+parameters+[javascript])… :-) – Bergi Feb 20 '15 at 00:14
  • 1
    No, just leave it. It will serve as a signpost for others who don't know the exact term. (and deleting questions is bad for your karma) – Bergi Feb 20 '15 at 00:21
  • 1
    No, the `.length` does not require the function to have a name. You just need a reference to the function object, the same as you need when you'd call it. Inside an IEFE you can use `arguments.callee`, but that is despised, better name your function; or just use a constant. – Bergi Feb 22 '15 at 19:03

2 Answers2

1

Yes. Example:

function main(a, b, c) {
    console.log(main.length);
}

main(1, 2);    

See this Fiddle

1

You can name your function expression[1] and use that reference to get the arity of the function via its .length property:

(function iefe(a, b, c) {
    console.log(arguments.length); // 2
    console.log(iefe.length); // 3
}(1, 2));

1: If you don't care about oldIE bugs. If you do and work in sloppy mode, arguments.callee might be a better option. Of course you can also use an identifier-leaking function declaration or variable assignment, or - as you always refer to the same function anyway - use a constant value.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • I don't think there's any improvement. If you want to refer to a function, naming it is the perfect solution - of course the name should not be arbitrary. – Bergi Feb 22 '15 at 22:25