4

Why doesn't JavaScript have a nullish-coalescing-assignment (??=) operator?

 2 years ago
source link: https://dev.to/baenencalin/why-doesnt-javascript-have-a-nullish-coalescing-assignment-operator-3jaj
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Calin Baenen

Posted on Mar 16

Why doesn't JavaScript have a nullish-coalescing-assignment (??=) operator?

JavaScript has ??, and is used by doing x ?? y.
The purpose of which is to replace null-like values with another, instead of ||, which favors the right hand side if the left is falsy, regardless of whether it is nullish or not.
To understand it better, read more about it on the Mozilla Developer Network, that can explain it better than me.

Anyways.
Where am I going with this?
... Well, if you look at the operators in JavaScript, you'll see a pattern with them:

a = a + b;    // Factorable to: a += b
a = a - b;    // Factorable to: a -= b
a = a ** b;   // You can even factor this to: a **= b

a = a ?? b;   // Can't be factored to: a ??= b
              // ...?

Enter fullscreen mode

Exit fullscreen mode

This isn't a big issue, but it would make the language more consistent.
Not only that, but it would be a nice way to clean up constructors. For example:

class Shape {
    constructor(x, y, w, h) {
        this.x = x ?? this.x;
        this.y = y ?? this.y;
        this.w = w ?? this.w;
        this.h = h ?? this.h;
    }

    // ...

    h = 0;
    w = 0;
    x = 0;
    y = 0;
}

// Could theoretically become...

class Shape {
    counstructor(x, y, w, h) {
        this.x ??= x;
        this.y ??= y;
        this.w ??= w;
        this.h ??= h;
    }
    // ...
}

Enter fullscreen mode

Exit fullscreen mode

As I said, it isn't a huge difference, but redundancy-removals similar to this are the reason += even exist in the first place.

So, I present to you the question posed in the title.
Why doesn't JavaScript have a nullish-coalescing assignment operator    (??=)?

Thanks for reading!
Cheers!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK