In JavaScript I often use the ||
operator to get the value of some property - or a default value. For instance:
var dens = mapping.defaultElementNamespaceURI||mapping.dens||'';
If mapping
has defaultElementNamespaceURI
, it will be used, otherwise look for dens
or use an empty string by default.
However if my property is boolean, it does not work:
var dom = mapping.allowDom || mapping.dom || true;
Returns true
even if mapping.dom
is false
.
I wonder, what would be the best (laconic but still readable) syntax for defaulting boolean properties? Defaulting in a sense that if the property is defined, use its value otherwise some provided default value. I can write a function for this, sure, but maybe there's someting as elegant as a || b || c
?
Code sample:
var a = {};
$('#result').text(a.boo||a.b||true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="result"></pre>
Update
Seems like there's no "syntactically sweet" way to do this, so I've resorted to writing a function:
var defaultValue = function()
{
var args = arguments;
if (args.length === 0)
{
return undefined;
}
else
{
var defaultValue = args[args.length - 1];
var typeOfDefaultValue = typeof defaultValue;
for (var index = 0; index < args.length - 1; index++)
{
var candidateValue = args[index];
if (typeof candidateValue === typeOfDefaultValue)
{
return candidateValue;
}
}
return defaultValue;
}
}
Considers the last argument to be the default value. Returns the first argument which has the same type as the default value.
a.x || b
will return the value of b if a.x is "falsey" -- undefined, empty string, 0, a few other values.
If you need to display something unless the field is in an object, even if the field's value is falsey, you have to say so explicitly.
'x' in a ? a.x : b
If you explicitly set a.x to undefined, that expression will return 'undefined', not b.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments