In JavaScript (only vanilla JS please), is there any way to “conditionally assign” a variable?
I googled “conditionally assign” and got answers involving the ternary operator, assigning one thing or another depending on a condition, so perhaps I’m using the wrong term.
I actually mean assign something or don’t assign anything (not even undefined) depending on either the result of a condition in general, or more specifically the existence or absence of a valid value being assigned.
For example, running this: (^)
const adventurer = { name: 'Alice', cat: { name: 'Dinah' } }; const adventurer2 = {}; adventurer2.name = 'Bob'; adventurer2.cat = adventurer?.dog?.name; console.log(adventurer2);
…produces:
Object { name: "Bob", cat: undefined }
But let’s say I want adventurer2.cat
to not be assigned anything (not even undefined
) in the above example — ie. no assignment to occur at all if dog.name doesn’t exist (or in the more general case, based on the result of some condition). So if the above did what I’m seeking, then the result would instead be:
Object { name: "Bob" }
Of course stuff like:
If (adventurer?.dog?.name !== undefined) adventurer2.cat = adventurer.dog.name;
…gives the result I’m seeking, but is there a shorter-hand way?
(I looked at logical nullish assignment and nullish coalescing operator but unless I’m missing something (am I?) they can’t do it.)
Thanks!
^Not particularly relevant to the question, but code borrowed and adapted from here
Advertisement
Answer
In ES6 you can use the inline if &&
for a cleaner way like the following:
let i; true && (i = 0); console.log(i); // 0
and returning to your code it would be:
const adventurer = { name: 'Alice', cat: { name: 'Dinah' } }; const adventurer2 = {}; adventurer2.name = 'Bob'; adventurer?.dog?.name && (adventurer2.cat = adventurer.dog.name;) console.log(adventurer2);