DEV Community

Discussion on: We don't need a ternary operator

 
glosswater profile image
lipgloss

how is making a binary decision operator abuse?

Thread Thread
 
maxart2501 profile image
Massimo Artizzu

Because what you actually want is an if-then-else path. The ternary operator has been conceived for that. Logical operators are for logical expression.

Sure you can use them to create conditional branching, but that doesn't make that any clearer. It's hiding the broken glass under the rug (i.e., not using the ternary operator for the sake of not using it, not because you're opting for a clearer pattern).

Thread Thread
 
glosswater profile image
lipgloss • Edited

Fair enough regarding clarity, though in that case we could say that the given example is at fault and not how we decide to return the result ;). It's true that rather than check if error is truthy, it'd be nicer to write something like reject(error) || resolve(data). (I know that doesn't make sense for promise resolution, but bear with me as it's just the example we're working with.)

Regarding "logical operators are for logical expression", the ternary operator's left hand side expression is already a logical expression by nature. Adding a syntax for deciding whether to go "left or right" that doesn't follow the same rules as any other operator in the language and worse, different from the ternary implementations in other, older languages can add confusion where there doesn't need to be.

All that aside, I love the ternary operator when writing, but during reviews, or walking people through later, what seemed so simple to me at the time of writing is rarely as clear. The logical or's result is immediately clear.

A pattern I also see (specifically in new React developers, I think) is returning null as the right hand operand for the ternary. I think it's a weird case of "the ternary operator is cool and I want my code to be concise". That added layer of "need to actually learn the ternary operator to write it" creates a desire to use and abuse it.

Edit, for clarity and stuff: As with everything in programming there's a time and place for everything. But if your goal is to have a single line, immediate "true or false" result of something, I feel the logical or is made for that. There's a small window where the ternary probably doesn't hurt anything but is ultimately the same as using multiple logical ors. Anything much larger or nested probably calls for actual if/else.