Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have seen this syntax in v15.0.1: &&=, ||= and ??=. But I don't know what it does. Does anyone know?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
516 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...