DEV Community

Saulo Dias
Saulo Dias

Posted on • Edited on

Ternary Operator: Better Alternatives

The ternary operator is a nice way to write concise value assignments without having to write a more lengthy if/else.
For example:

// This...
let value;
if (test) value = 1;
else value = 2;

// can be written as this:
const value = test ? 1 : 2;
Enter fullscreen mode Exit fullscreen mode

However it's easy to misuse the ternary operator for things where simpler operators could often have been a better choice. So here are some alternatives for common mistakes.

Static true/false assignments:

const value = test ? true : false;
// can be replaced by boolean casting:
const value = !!test;
// or even
const value = Boolean(test); // I prefer the shorter alternative
Enter fullscreen mode Exit fullscreen mode

Nullable assignment (falsy case)

const value = test ? test : null;
// can be written like this
const value = test || null;
Enter fullscreen mode Exit fullscreen mode

Note: The code above will return null as long as test is falsy.

Nullable assignment (nullish case)

const value = test !== null || test !== undefined ? test : null;
// can be written like this:
const value = test ?? null;
Enter fullscreen mode Exit fullscreen mode

See: Nullish coalescing operator (??)

By the way...

const test = a === null || a === undefined;
// can be simplified as:
const test = a == null;
Enter fullscreen mode Exit fullscreen mode

Checking for undefined

I have seen this a few times. I promise.

const value = obj ? obj.a : undefined;
// which can simply be:
const value = obj && obj.a;
// or in more recent implementations:
const value = obj?.a;
Enter fullscreen mode Exit fullscreen mode

See: Optional chaining (?.) [elvis operator]

Beware of browser coverage. If you want to use optional chaining safely, it might be a good idea to use TypeScript configured to transpile the code to ES5 with the modules configured to esnext, to use the latest ECMAScript features.

The ternary (but not actually ternary) operator

This is my favorite one, and also an honest mistake. Some people get overexcited with the simplicity of the ternary operator and might think it is just a "shorter" if/else statement.

let value;
test ? value = 8 : null;
// when they meant 
if (test) value = 8;
Enter fullscreen mode Exit fullscreen mode

The single-line if statement is simple and clean enough for that purpose, and we know test ? value = 8 will not work. The ternary operator needs to have an else return value. If you don't need it, use a single-line if.

Another variant

In React, sometimes when we want to render a component if a specific condition is true, we might see something like this.

{ myCondition ? <MyComponent /> : null }
// when they meant 
{ myCondition && <MyComponent /> }
Enter fullscreen mode Exit fullscreen mode

I would only use a ternary operator for the example below in the case I want to render one component or another.

Wrapping up...

In a nutshell, if your ternary operator does not have a structure like the one below, you should raise an eyebrow and check if there really aren't other simpler alternatives.

const value = test ? otherValue : anotherValue;
Enter fullscreen mode Exit fullscreen mode

Can you think of other examples you have seen of poor use of the ternary operator? Please let me know in the comments below.

Top comments (4)

Collapse
 
grahamthedev profile image
Info Comment hidden by post author - thread only accessible via permalink
GrahamTheDev

Great list, just be careful with Optional chaining, support is only around 90%.

Also what is "The ternary operator with disability" meant to be as I don't think that is a common term and as it reads it comes across as something that could be offensive.

I understand that could just be a language issue so I thought I would ask.

Collapse
 
saulodias profile image
Saulo Dias • Edited

Great list, just be careful with Optional chaining, support is only around 90%.

Excellent observation.

I have edited out that bad attempt at humor. I'll try and keep my questionable sense of humor away from my posts. Sorry about that, and thanks for the feedback.

Collapse
 
juniordevforlife profile image
Jason F

I am guilty of using ternary operator when I could probably use something else. Great read, I'll work on incorporating these ideas.

Collapse
 
encarvlucas profile image
Lucas Carvalho de Sousa

Great content!

Some comments have been hidden by the post's author - find out more