Set Default Variable Value in JavaScript
- 1 minute read
Did you know that you can set a default variable value in JavaScript?
Here is an example declaration statement, where foo
is set to bar
if bar
is defined, but otherwise set to Default Value
:
var bar;
const foo = bar || `Default Value`;
Because bar
is
undefined in the above example, foo
is set to Default Value
.
In the above example, a string is used for the default value, but any data type can be used to the right of the ||
operator.
Here is another way of visualizing how this works:
const foo = undefined || `Default Value`;
If the value to the left of the ||
operator evaluates to undefined
, then the variable is set to the value to the right of the ||
operator.
But if the value on the left does not evaluate to undefined
, then the variable will be set to the value on the left.
Conclusion
There are technically a few other ways to go about doing this, but I’ve found this method to be very versatile.
This method also works if the value on the left side of the ||
operator evaluates to false
instead of undefined
.