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
// ...?
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;
}
// ...
}
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 (??=
)?
Top comments (2)
Because it has already the operator:
developer.mozilla.org/en-US/docs/W...
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):
(
10
and25
should be logged, but10
gets logged twice, instead.)