So the nullish coalescing assignment operator ??=
assigns the value to the variable only if the current stored value is nullish.
Maybe I'm missing the obvious but I can't think of a slick solution (without if statements) to only assign if the right-hand side value being assigned is not nullish?
I'm using nodeJS to give a bit more context.
I want
let x r??= 2;
// Updates 'x' to hold this new value
x r??= undefined;
// Has no effect, since the value to assign is nullish
console.log(x); // 2
EDIT to give more clarity to my problem:
I want a variable only to be assigned a new value, if that new value is not nullish.
let iceCream = {
flavor: 'chocolate'
}
const foo = 2.5
const bar = undefined;
iceCream.price r??= bar
// does not assign the new value because it is nullish
console.log(iceCream.price) // expected to be error, no such property
iceCream.price r??= foo
// assigns the new value because it is not nullish but a float
console.log(iceCream.price) // expected to be 2.5
iceCream.price r??= bar
// does not assign the new value because it is nullish
console.log(iceCream.price) // expected to still be 2.5
x ??= undefined
already do exactly that? – Zondrax ?? = undefined
assignsx
to undefined ifx
is nullish. OP wants to assign ifx
is not nullish. – Scarx
to the right hand side operant, if the right hand side operant is not nullish (not whenx
is not nullish). Though my initial comment wont work, because it will still remain unmodified if both values are not nullish (ifx
is2
and you usex ??= 3
, it'll remain2
instead of assigning3
). – Zondraundefined
value/property however does throw errors.) – Zondrax = newVal ?? x;
. AssignsnewVal
ifnewVal
is anything exceptnull
orundefined
, even falsy values (0
,NaN
, etc...). In all other cases, assignsx
, which keeps it unchanged. For objects you can dox.foo = newVal ?? x.foo;
, obviously. – Xever