Nested ternarys can be hard to read for other developers

Be careful with nested ternarys as they can impact code readability.
For example I know what 👇🏻 …

var comparison = (a > b) ? "a is greater than b" : (a < b) ? "b is greater than a" : "a is equal to b";

does but I have to ‘think’ about it. I don’t like it when other developers make me think about code, I prefer to just read it.

Unfortunately I see this all the time, devs think its ‘better’ or more ‘clever’ because its only one line of code.

Unless performance micro optimization is an issue the focus should always be on code readability for the next developers. In this case perhaps a simple if/else or switch statement would be clearer.

Leave a Reply

Your email address will not be published.