Javascript equivalent of Python's dict.setdefault?
if (!('key' in d)) d.key = value;
or
'key' in d || (d.key = value);
(The last one uses the short-circuit behavior of conditional expressions.)
"d.key || (d.key = value)
" suggested in the other answer is buggy: if an element exists but evaluates to false
(false
, null
, 0
, -0
, ""
, undefined
, NaN
), it will be silently overwritten.
While this might be intended, it's most probably not intended for all of the aforementioned cases. So in such a case, check for the values separately:
if (!('key' in d) || d.key === null) d.key = value;
It's basically like using an if
statement, but shorter:
d.key || (d.key = value);
Or
d.key = d.key || value;
Update: as @bobtato noted, if the property is already set to the value false
it would overwrite it, so a better way would be:
!d.key && d.key !== false && (d.key = value);
Or, to do it as he suggested (just the shorthanded version):
'key' in d || (d.key = value);
// including overwriting null values:
('key' in d && d.key !== null) || (d.key = value);
There is nothing built-in, but this function will do it:
function setDefault(obj, prop, deflt) {
return obj.hasOwnProperty(prop) ? obj[prop] : (obj[prop] = deflt);
}
If obj
will only contain non-falsy values, obj[prop] || (obj[prop] = deflt)
is a fine simple alternative (but deflt
will override anything falsy). This has the added advantage that deflt
will only get evaluated when its value is needed, so it's OK for it to be an expensive expression.