Extension on logical assignment operators

hello everyone!

I might have a good suggestion on improving the logical assignment operators. Currently it evaluates the variable and assigns if its truthy, falsey or equals, but what if you want to evaluate the next value and take action afterwards. For example:

const getNextValue = () => {
  if (...) {
    return undefined;

  return 'ourNextString';

let varx = 'hello';
// all of the statements below evaluate varx
varx ||= getNextValue(); // a will always be 'hello';
varx &&= getNextValue(); // a will always be 'hello';
varx &&= getNextValue(); // a will always be getNextValue();

I want to propose a way to evaluate the next value:

// so instead of only being able to do:
varx && (varx = getNextValue());

// I propose we should also be able to do:
getNextValue() && (varx = getNextValue());
// or in a slighty better way, to not call the function twice
varx = getNextValue() ?? varx;

// maybe it could work to flip it around, like:
varx =|| getNextValue();
varx =&& getNextValue();
1 Like

From what I understand, your idea is to basically make logical assignment operators work when reversed, to allow for the use of =||, =&& and =??. If that's the case then I totally agree with this and I would love to see this be implemented, as it would be really useful to make it easier to check if something exists before assigning a variable to it, or do other similar checks.

This seems like it'd be better suited for an optional pipeline operator than an assignment operator.

Edit: If you were to blend that with this suggestion, it might look like this:

// varx = varx != null ? getNextValue() : varx
varx |?>= getNextValue()