.= Operator

I have had I really simple idea for a while, and that is the .= operator. It would be simmilar to the +=, -=, /=, *= operators, except it is based on the supplied object. I am bad at explaining, so here is what I mean:

Right now I have to do this

this.objects.player.position.vector = this.objects.player.position.vector.add(vel);

Now I could create a variable,

const player = this.objects.player.position.vector;
player = player.add(vel);

But, this falls apart for types that are copied and not referenced.

What I propose is this:

this.objects.player.position.vector .= add(vel);

This expands to the first code block:

this.objects.player.position.vector = this.objects.player.position.vector.add(vel);

The .= operator takes whatever value is on the left, and looks for whatever is on the right in the prototype or in the object itself and applies that to the object on the left, then sets the object on the left to the final result. This is useful for things like array.map or functions that return a new object instead of modifying the original one.

How often do you find that fluent interfaces return a new value, as opposed to running side-effects or mutating the receiver?

For arrays, there's map and friends of course, but there's also .reverse(), .sort(), .fill(), .splice(), etc that mutate the original (and only some of these return this).

1 Like

Well I mean its not limited to arrays, it could be custom objects or classes, or another one that comes to mind is string.toLower/UpperCase(). It would really just be syntactic sugar for methods like that.

Have a look at Why isn't there a .= operator? for some arguments against doing this.

1 Like