In Python, for a dictionary d
,
JavaScript
x
2
1
d.setdefault('key', value)
2
sets d['key'] = value
if 'key'
was not in d
, and otherwise leaves it as it is.
Is there a clean, idiomatic way to do this on a Javascript object, or does it require an if
statement?
Advertisement
Answer
It’s basically like using an if
statement, but shorter:
JavaScript
1
2
1
d.key || (d.key = value);
2
Or
JavaScript
1
2
1
d.key = d.key || value;
2
Update: as @bobtato noted, if the property is already set to the value false
it would overwrite it, so a better way would be:
JavaScript
1
2
1
!d.key && d.key !== false && (d.key = value);
2
Or, to do it as he suggested (just the shorthanded version):
JavaScript
1
6
1
'key' in d || (d.key = value);
2
3
// including overwriting null values:
4
5
('key' in d && d.key !== null) || (d.key = value);
6