DEV Community

Cover image for If not ternary operator then what?
NisarShaikh
NisarShaikh

Posted on

If not ternary operator then what?

Like many languages, JavaScript has the conditional (ternary) operator. What's wonderful about this operator is that it can be nested in expressions and it returns a value.

So what is the right way to use it in JavaScript?

Should we try to avoid it?

While writing code I found something that can replace ternary operator under certain conditions.

Traditional use:

const foo = a ? a : b;
const bar = c ? true : false;
const baz = c ? flase : true;
Enter fullscreen mode Exit fullscreen mode

What I found was:

const foo = a || b;
const bar = !!c;
const baz = !c;
Enter fullscreen mode Exit fullscreen mode

There is one more, && (AND) operation.

const boo = a `&&` 'Hello';
Enter fullscreen mode Exit fullscreen mode

Here the AND operator will short-circuit if the left operand is false, it acts identically to the first part of the ternary operator.

Do you know more? Please do let me know in the comments.

Top comments (4)

Collapse
 
alainvanhout profile image
Alain Van Hout

Be careful with using && for fallbacks, since you need to keep in mind what counts as a falsy value in JavaScript (that includes e.g. an empty string or empty array, while you might have written the code with the expectation of getting either a (non-empty) array or null).

Collapse
 
jenbutondevto profile image
Jen

ES2020 now has the nullish coalescing operator ??. If the left operand is null or undefined, the right hand operand is used, if it’s not, then the left

const coalesced = undefined ?? 42
// 42
Enter fullscreen mode Exit fullscreen mode
Collapse
 
devdufutur profile image
Rudy Nappée • Edited

You can also use Boolean(val) instead of !!val. It may be more readable.

Collapse
 
andreidascalu profile image
Andrei Dascalu

If You need a Boolean evaluation, there is definitely no need for ternary operator.

However, there is also = c ? a:b