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?
The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.
To declare optional function parameters in JavaScript, there are two approaches: Using the Logical OR operator ('||'): In this approach, the optional parameter is Logically ORed with the default value within the body of the function. Note: The optional parameters should always come at the end on the parameter list.
Using the Logical OR operator ('||') In this method, the optional parameter is "Logically ORed" with the default value within the body of the function. In the example below, if the value of b is undefined, 2 is passed instead.
In JavaScript, function parameters default to undefined . However, it's often useful to set a different default value. This is where default parameters can help.
Your logic fails if optionalArg is passed, but evaluates as false - try this as an alternative
if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }
Or an alternative idiom:
optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;
Use whichever idiom communicates the intent best to you!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With