Skip to content

Is there a way to use the condition of a ternary to be the value?

I run into a lot of cases where I would like to use the condition of a ternary as the actual value of its output. Is there a way to do this without having to say the condition again?

For example: var thing = veryCoolThingExistsButItsNameIsVeryLong ? veryCoolThingExistsButItsNameIsVeryLong : otherThing;

What I want is something that looks more like this: var thing = veryCoolThingExists?otherThing; where thing is assigned otherThing only if veryCoolThingExists doesn’t exist.



You can use the logical OR operator, ||,

var thing = veryCoolThingExistsButItsNameIsVeryLong || otherThing;

which returns the first value if it’s truthy or the second if not.

User contributions licensed under: CC BY-SA
4 People found this is helpful