ES6 Feature: Optional Function Parameters
The conventional approach to optional function parameters in JavaScript involves a logical OR (||) check, exemplified in the code snippet below:
function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff }
While this technique has been the traditional method, it has certain limitations. For instance, if optionalArg is passed but evaluates as false, the default value is not assigned.
Alternative Approaches
To address this limitation, two alternative approaches are suggested:
1. Type Checking:
if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }
This approach involves checking if optionalArg is undefined and assigning the default value if this condition is met. It ensures that the default value is set only when optionalArg is absent or when it is explicitly set to undefined.
2. Ternary Operator:
optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;
The ternary operator provides a concise alternative for handling optional parameters. The expression evaluates to the default value if optionalArg is undefined; otherwise, it retains the original value of optionalArg.
Which to Choose?
Both the type checking and ternary operator approaches offer effective solutions to the issue of optional parameters. The choice between them depends on personal preference and code readability. The ternary operator's syntax is more compact, while the type checking approach may be more explicit.
The above is the detailed content of How to Handle Optional Function Parameters in ES6: Type Checking vs. Ternary Operator?. For more information, please follow other related articles on the PHP Chinese website!