简体   繁体   中英

Is there a reverse logical nullish assignment?

So the ??= 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 value 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

No, that's not a single operator. The closest is two operators:

x = undefined ?? x;

You could use logical AND assignment .

From the MDN Web Docs:

let a = 1;
let b = 0;

a &&= 2;
console.log(a);
// expected output: 2

b &&= 2;
console.log(b);
// expected output: 0

Adding another answer after clarification as editing my previous one seemed weird.

The simplest way I can think of a solution without if is as follows:

let iceCream = {
    flavor: 'chocolate'
}

const foo = 2.5
const bar = undefined;
bar && (iceCream.price = bar)
// Another possible solution if creating the property with a nullish value is ok for you:
iceCream.price = bar || iceCream.price;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM