Set a default parameter value for a JavaScript function
Modern JavaScript accommodates default parameters by equipping functions with pre-set values:
If b
is absent, JavaScript automatically defaults to 5
. It's a powerful mechanic for crafting cleaner functions with predictable outcomes.
Core concept: Only undefined triggers defaults
Default values kick in solely when arguments are either undefined
or simply not provided. This creates a distinction from the older ||
assembly, which could result in misleading outcomes:
Default parameters with destructuring
Ride the ES6 wave even further with destructuring. Below is a combination of destructuring and default values:
Indeed, we've got named parameters that not only enhance churned out code's readability, but also clarify function signatures.
Diverse default expressions
ES6 avails a luscious buffet of expressive possibilities, incorporating any expression (including function calls!) as default parameters:
Such flexibility can gracefully navigate around absent callbacks, enhancing robustness.
Traditional JavaScript strategy
For those still brooding around in legacy nests, typeof
can be employed to assign defaults without upsetting valid yet falsey values:
Default wrangling with destructuring
When default parameters meet, mate, and meld with destructuring, we've got a recipe for tackling complex scenarios with ease and aplomb:
This bolsters code reusability and unclutters prop management.
Null values: The notorious exception
A notable peculiarity emerges when a null
value is passed as it does not trigger the default, deemed as a valid value:
For such cases, an explicit check for null
is always a safe bet.
Shorthand utilities for managing defaults
For complex defaulting conditions, shorthand utilities like Object.assign()
or lodash's _.defaults()
come handy to merge defaults and provided parameters seamlessly:
Was this article helpful?