ES12:Nullish 合并运算符和对象

ES12: Nullish coalescing operators & objects

例如我有这样一个对象:

const a = {
 b: "value"
 // and also what about: c: '', or c: 0, c: false ?
};

而且我想为我的对象分配一个 'c',但前提是之前没有分配它。

通常我们会这样做:

if (!a.c) {
  a.c = 1; // or without { } for a bit shorty way.
}

但是 ES12 标准引入了更多新的 Nullish 合并和逻辑运算符,所以有人可以向我解释它如何帮助我替换上面的示例以及 null0 作为数字行为(空字符串和 false 行为也是一个加号)?

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)

仅当左侧的值为undefinednull时,logical nullish assignment ??=才赋值。

a.c ??= 1;

如果您想替换任何 falsy value, like '', 0, false, null, undefined, you could take the logical OR assignment ||=

a.c ||= 1;