Chaining assignment operator

There's a bunch of assignment operators already: a few are listed below.

  • Bitwise assignment operators such as ^=, &=, |=, >>>=, and a few more;
  • Mathematical assignment operators such as +=, /=, **=, %=, and a few more;
  • Logical assignment operators &&=, ??=, ||=

These syntaxes all come down to the following being equivalent:

foo [operator]= bar
// is equivalent to
foo = foo [operator] bar

Sometimes, I wish I would have this for chaining; i.e. shortening foo = foo.bar to foo .= bar. I don't think this syntax could be misinterpreted (not by parsers, anyways - I could see some people coming from PHP confusing it for string concatenation).

Two example situations in which this would be helpful:

products .= filter(product => product.stock > 0);

and (slightly more complex):

let node = someElement;
let index = 0;
while(node){
    node .= previousSibling;
    index++;
}

Perhaps this is extendable to include the optional chaining assignment operator, ?.= (where foo ?.= bar would be equivalent to, you guessed it, foo = foo?.bar).

2 Likes

Hi @vrugtehagel

Possible duplicate of .= Operator

I do like the idea of being able to use functions such as filter() in a self-modifying way.

But, I do find the syntax a bit confusing, because, unlike other operators, the "." takes an identifier on the right, not a value.

const filter = () => ...
x += filter(...)   // Uses the local filter function
x ??= filter(...) // Uses the local filter function
x .= filter(...)  // This filter is a property of x

x += (fn1() + fn2())  // Valid syntax
x ??= (fn1() + fn2()) // Valid syntax
x .= (fn1() + fn2())  // Doesn't work, .= needs an identifier to operate on, not a value.