Skip to content
Advertisement

Javascript equivalent of Python’s dict.setdefault?

In Python, for a dictionary d,

JavaScript

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

Or

JavaScript

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

Or, to do it as he suggested (just the shorthanded version):

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement