# Code Smell 201 - Nested Ternaries

> TL;DR: Don't use nested IFs or nested ternaries

# Problems

- Readability

- Default Case

# Solutions

1. Rewrite the code as an IF condition with an early return

# Context

Nesting is always a problem with complexity. 

We can fix it with polymorphism or early returns

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/45754a6d586d067627c4796748686384)

```javascript

const getUnits = secs => (
 secs <= 60       ? 'seconds' :
 secs <= 3600     ? 'minutes' :
 secs <= 86400    ? 'hours'   :
 secs <= 2592000  ? 'days'    :
 secs <= 31536000 ? 'months'  :
                    'years' 
)

```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/4ac913c6d842c4f0fc9d8e9998348335)

```javascript

const getUnits = secs => {
 if (secs <= 60) return 'seconds'; 
 if (secs <= 3_600) return 'minutes'; 
 if (secs <= 86_400) return 'hours';   
 if (secs <= 2_592_000) return 'days';    
 if (secs <= 31_536_000) return 'months';  
 return 'years' 
}

// More declarative

const getUnits = secs => {
 if (secs <= 60) return 'seconds'; 
 if (secs <= 60 * 60) return 'minutes'; 
 if (secs <= 24 * 60 * 60) return 'hours';   
 if (secs <= 30 * 24 * 60 * 60) return 'days';    
 if (secs <= 12 * 30 * 24 * 60 * 60) return 'months';  
 return 'years' 
}

```

# Detection

[X] Automatic 

Linters can detect this complexity using parsing trees.

# Tags

- IFs

# Conclusion

We must deal with [accidental complexity](https://maximilianocontieri.com/no-silver-bullet) to improve code readability.

# Relations

%[https://maximilianocontieri.com/code-smell-133-hardcoded-if-conditions]

%[https://maximilianocontieri.com/code-smell-78-callback-hell]

%[https://maximilianocontieri.com/code-smell-102-arrow-code]
 
# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [NIKHIL](https://unsplash.com/@vinikhill) on [Unsplash](https://unsplash.com/photos/pThIEv416pE)
  
* * *

> One of the best things to come out of the home computer revolution could be the general and widespread understanding of how severely limited logic really is.

_Frank Herbert_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
