Javascript equivalent of Python’s dict.setdefault

dictionaryjavascript

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?

Best Answer

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;