The logical nullish assignment ??= assigns the value only if the value of the left hand side is either undefined or null.
a.c ??= 1;
If you like to replace any falsy value, like '', 0, false, null, undefined, you could take the logical OR assignment ||=.
a.c ||= 1;
Answer from Nina Scholz on Stack OverflowVideos
does this API call get executed even if
myDatais non-null?
No, it will not be executed.
myData ??= await fetch("API")
is equivalent to
myData ?? (myData = await fetch("API"))
So, only if the first expression myData is nullish, the second assignment part runs.
let value = "test"
value ??= null.toString() // doesn't throw error because it is not executed
console.log(value)
value = null
value ??= null.toString() // throws error
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
The answer is no. details
The error means your version of Node does not yet have support for the ??= operator.
Check out the versions which support it on node.green:
It's possible for node version v15.14+.
The rewrite for something like
a.greeting ??= "hello"
in node <v15.14 is:
a.greeting = a?.greeting ?? 'hello'
Maybe it does help someone :]
So, JavaScript has x ?? y, which favors the right-hand side if the left one is undefined or null.
However, an oddity that's present with this operator is it's assignment-form.
In JavaScript, most operators have an assignment form + has +=, - has -=, heck, even ** the exponential operator has an assignment-form, and you can probably guess what that looks like.
However, ??= is conveniently absent.
This isn't a huge deal, but it makes the language a little inconsistent, along with that, it would make as a small way to remove redundancy from class-constructors:
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;
}
// Class body...
}
// Could theoretically become...
class Shape {
counstructor(x, y, w, h) {
this.x ??= x;
this.y ??= y;
this.w ??= w;
this.h ??= h;
}
// Class body....
}
And since small factorizations like this are the reason why even have +=, I pose to you a question identical to that of the one in the title:
Why do you think JavaScript doesn't have a nullish-coalescing assignment operator?