'Ternary Shorthand to Assign the Condition?

Is there any type of shorthand when using ternary assigns to say "return the condition?"

You use ternary in javascript as so:

const cityMayor = country?.state?.county?.city?.mayor
  ? country.state.county.city.mayor
  : "Open for vote";

Is there a way to say "use the condition?"

e.g. Does something like this exist:

const cityMayor = country?.state?.county?.city?.mayor
  ? <- 
  : "Open for vote";

To avoid having to retype everything in the true condition, return the condition as the true evolution?

I know I can write a method to do this for me, but is there anything built-in that does this?

I know I can do this, but I don't want to have to constantly import it:

const tAssign = (c, e) => {
  return c ? c : e;
}

const cityMayor = tAssign(country?.state?.county?.city?.mayor, "Open for vote");



Solution 1:[1]

You can use null coalescing:

country?.state?.county?.city?.mayor ?? "Open for vote"

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

Solution 2:[2]

You can use:

const item = country?.state?.county?.city?.mayor || "Vince McMahon";

But in some specific cases and frameworks, like React Native for example, it's strong recommended to avoid this, using the ternary operator (event it's not look to good) the avoid problems with rendering.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cboston
Solution 2 Luiz Felipe Laviola