Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...