This question already has an answer here:
I've always handled optional parameters in JavaScript like this:
function myFunc(requiredArg, optionalArg){
optionalArg = optionalArg || 'defaultValue';
// Do stuff
}
Is there a better way to do it?
Are there any cases where using ||
like that is going to fail?
During a project I noticed I was repeating myself too much with the optional parameters and settings, so I made a class that handles the type checking and assigns a default value which results in neat and readable code. See example and let me know if this works for you.
Using this class:
arg || 'default'
is a great way and works for 90% of casesIt fails when you need to pass values that might be 'falsy'
false
0
NaN
""
For these cases you will need to be a bit more verbose and check for
undefined
Also be careful when you have optional arguments first, you have to be aware of the types of all of your arguments
In all cases where optionalArg is falsy you will end up with defaultValue.
All of the above log defaultValue, because all of 6 are falsy. In case 4, 5, 6 you might not be interested to set optionalArg as defaultValue, but it sets since they are falsy.
Loose type checking
Easy to write, but
0
,''
,false
,null
andundefined
will be converted to default value, which might not be expected outcome.Strict type checking
Longer, but covers majority of cases. Only case where it incorrectly assigns default value is when we pass
undefined
as parameter.Checking arguments variable
Catches all cases but is the most clumsy to write.
ES6
Unfortunately this has very poor browser support at the moment
I suggest you to use ArgueJS this way:
You can also replace
undefined
by the type of the argument you expect to receive, like this:Landed to this question, searching for default parameters in EcmaScript 2015, thus just mentioning...
With ES6 we can do default parameters: