Home >Web Front-end >JS Tutorial >How to Safely Handle Optional Function Parameters in JavaScript?
Using Conditional Statements for Optional JavaScript Function Parameters
In JavaScript, it's common to use conditional statements to handle optional function parameters. Here's the example you provided:
<code class="javascript">function myFunc(requiredArg, optionalArg){ optionalArg = optionalArg || 'defaultValue'; // Do stuff }</code>
However, this approach can fail if the optional argument is passed but evaluates to false (e.g., empty string, 0). Here's a safer alternative:
<code class="javascript">if (typeof optionalArg === 'undefined') { optionalArg = 'default'; }</code>
This checks if the optional argument is undefined, in which case it assigns a default value.
Alternatively, you can use the conditional (ternary) operator:
<code class="javascript">optionalArg = (typeof optionalArg === 'undefined') ? 'default' : optionalArg;</code>
This idiom is more concise but conveys the same intent as the if statement.
Choose the idiom that best suits your preference and communicates the intended behavior clearly.
The above is the detailed content of How to Safely Handle Optional Function Parameters in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!