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

Categories

0 votes
533 views
in Technique[技术] by (71.8m points)

javascript - What purpose do &&=, ||= and ??= serve?

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

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...