DEV Community

Calin Baenen
Calin Baenen

Posted on

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!

Top comments (2)

Collapse
 
midudev profile image
Miguel Ángel Durán 👨‍💻

Because it has already the operator:
developer.mozilla.org/en-US/docs/W...

Collapse
 
calinzbaenen profile image
Calin Baenen

Oh, whenever I try(ed) to use it, it gives me an error in NodeJS.
And in browser JavaScript, something doesn't seem quite right with its behavior (unless it's just SoloLearn acting up):
It should log  raw `10` endraw  and  raw `25` endraw , but it logs  raw `10` endraw  twice, instead.
(10 and 25 should be logged, but 10 gets logged twice, instead.)