These are the new logical assignment operators. They're similar to the more familiar operators like *=
, +=
, etc.
someVar &&= someExpression
is roughly equivalent to someVar = someVar && someExpression
.
someVar ||= someExpression
is roughly equivalent to someVar = someVar || someExpression
.
someVar ??= someExpression
is roughly equivalent to someVar = someVar ?? someExpression
.
I say "roughly" because there's one difference - if the expression on the right-hand side isn't used, possible setters are not invoked. So it's a bit closer to:
someVar &&= someExpression
is like
if (!someVar) {
someVar = someExpression;
}
and so on. (The fact that a setter isn't invoked is unlikely to have an effect on the script, but it's not impossible.) This is unlike the other traditional shorthand assignment operators which do unconditionally assign to the variable or property (and thus invoke setters). Here's a snippet to demonstrate:
const obj = {
_prop: 1,
set prop(newVal) {
this._prop = newVal;
},
get prop() {
return this._prop;
}
};
// Setter does not get invoked:
obj.prop ||= 5;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…