Skip to content
Advertisement

Javascript equivalent of Python’s dict.setdefault?

In Python, for a dictionary d,

d.setdefault('key', value)

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:

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);
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement