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;