What is the difference between these two ways of checking the arguments?
function foo(a, b) {
this.a=a;
this.b=b;
}
Using:
if (arguments.length === 1) {}
or
if (this.b !== undefined) {}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you want to check mandatory arguments, I will use
arguments.lengthas first step. If you want to check optional arguments, usually the pattern is:Notice that this works only if the parameters can’t be “falsy” values (so, empty string, zero, null, undefined, false, NaN). For example, if you pass an empty string as
aparameter, you will have foo. If you want to consider onlyundefinedas value for considering a parameter optional then you have to do something like:If you want to consider both null and undefined and optional parameter, you can have:
Of course, you can also use the operator
typeof. For instance you want thatacan be only a string:You can also force
ato be always a string, in the worst scenario will be the string version of the non-string value given (undefined as well):More complex cases have some utility functions that makes all this check for you, where you said the arguments required, the optional, the default value, etc.