How can I declare optional function parameters in JavaScript?
Handle optional parameters in JavaScript through default parameters. You can set defaults right in the function signature:
In this case, param
defaults to 'default'
when it's not explicit, making function calls easy and reducing logic inside the function.
ES6 default parameters
ES6 provides a sleek way to handle optional parameters by supporting default values:
ES6 Vs ES5 default values
ES6 only uses the default value if no argument was passed or if it's undefined
. But in ES5, developers made use of ||
operator for default values:
Be aware, though, that this method doesn't differentiate between null
, false
, 0
, or ''
and undefined
- all are falsy values. ES6's default parameters only activate if the value is undefined
.
Dealing with exceptions
ES6 does not consider null
as undefined
, hence, they don't trigger default parameter handling. For more robustness against falsy values, add parameter checking:
In an ES5 context, check if the value is undefined
:
Pitfalls
Mismanaged optional parameters can lead to unclear function usage or unforeseen behaviors. Overhauling functions with many optional parameters may muddle your function's purpose, especially if parameters cause side effects or require complex fiddling before use.
Use of truthiness in JS
Understanding truthy and falsy is essential when handling default parameters in pre-ES6 environments. Before the advent of default parameters, checking for undefined
was mission-critical.
Check optional parameters first
It's common practice to validate optional parameters first in your function body for robustness and clarity.
Handling unknown parameters
If you don't know the number of optional parameters, the arguments
object can come to rescue:
References
Was this article helpful?