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?
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?
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