For example I have an object like this:
const a = {
b: "value"
// and also what about: c: '', or c: 0, c: false ?
};
And I'd like to assign a 'c', key to my object, but only if it's not assigned before.
Usually we do something like this:
if (!a.c) {
a.c = 1; // or without { } for a bit shorty way.
}
But ES12 standards introduce a bit more new Nullish coalescing and logical operators, so can someone explain to me how does it help me with replacing the example above and what about null
and 0
as a number behavior (empty string and false
behavior is also a plus)?
The real question behind it, is about: can use of this new feature really could cover all the cases and replace the example above in real-production projects, or is it still better to stay in a more traditional way. (Of, course it's all about syntax sugar staff, but I'd like to know more about coverage)
CodePudding user response:
The logical nullish assignment ??=
assigns the value only if the value of the left hand side is either undefined
or null
.
a.c ??= 1;
If you like to replace any falsy value, like ''
, 0
, false
, null
, undefined
, you could take the logical OR assignment ||=
.
a.c ||= 1;