Ternary Operator: Better Alternatives
Tags: javascript, typescript, cleancode, codequality
Published: 2021-07-01 03:35:15

The ternary operator is a nice way to write concise value assignments without having to write a more lengthy `if/else`.
For example:
```typescript
// This...
let value;
if (test) value = 1;
else valeu = 2;

// can be written as this:
const value = test ? 1 : 2;
```
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:
```typescript
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
```

### Nullable assignment (falsy case)
```typescript
const value = test ? test : null;
// can be written like this
const value = test || null;
```
> Note: The code above will return null as long as `test` is *falsy*.

### Nullable assignment (nullish case)
```typescript
const value = test !== null || test !== undefined ? test : null;
// can be written like this:
const value = test ?? null;
```
> See: [Nullish coalescing operator (??)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator)

By the way...
```typescript
const test = a === null || a === undefined;
// can be simplified as:
const test = a == null;
```

### Checking for undefined
I have  seen this a few times. I promise.
```typescript
const value = obj ? obj.a : undefined;
// which can simply be:
const value = obj && obj.a;
// or in more recent implementations:
const value = obj?.a;
```
> See: [Optional chaining (?.) [elvis operator]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)

Beware of [browser coverage](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining#browser_compatibility). 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.
```typescript
let value;
test ? value = 8 : null;
// when they meant 
if (test) value = 8;
```
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.

```typescript
{ myCondition ? <MyComponent /> : null }
// when they meant 
{ myCondition && <MyComponent /> }
```

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.
```typescript
const value = test ? otherValue : anotherValue;
```

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