1

Having an object with 2 possible methods, is there an easy way to check if the method accepts a parameter or not, using pure javascript:

getItems(id) {...};
getItems() {...};

would like to check if the method accepts the id parameter or not?

GG.
  • 21,083
  • 14
  • 84
  • 130
emvidi
  • 1,210
  • 2
  • 14
  • 18

1 Answers1

10

You can get the number of formal parameters (the arity) from the length property of the function:

function zero() { }
function one(a) { }
console.log(zero.length); // 0
console.log(one.length);  // 1

In JavaScript, this is distinct from the number of arguments it was actually called with on any given specific occasion, which you can get from the arguments pseudo-array within the function (or in ES2015+, by using a rest parameter and getting its length).

Speaking of ES2015, a rest parameter doesn't add to the arity, so:

function stillOne(a, ...rest) { }
console.log(stillOne.length); // 1

Similarly, a parameter with a default argument doesn't add to the arity, and in fact prevents any others following it from adding to it (they're assumed to have a silent default of undefined):

function oneAgain(a, b = 42) { }
console.log(oneAgain.length);    // 1

function oneYetAgain(a, b = 42, c) { }
console.log(oneYetAgain.length); // 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • thank you T.J. Crowder, this solved my problem, don't know why I missed the already answered question: http://stackoverflow.com/questions/4848149/get-a-functions-arity – emvidi Dec 13 '16 at 19:14
  • No worries -- happy to delete this so you can delete the question if you prefer. (Happy to leave it if you prefer.) – T.J. Crowder Dec 13 '16 at 19:16
  • 1
    I prefer to keep it, thanks – emvidi Dec 13 '16 at 19:17