Search code examples
javascriptnode.jsoperators

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


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


Solution

  • 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;

    ??, if you aren't familiar with it, is the nullish coalescing operator. It will evaluate to the right-hand side if the left-hand side is either null or undefined.