re: We don't need a ternary operator VIEW POST

FULL DISCUSSION
 

I've found one good use for the ternary operator: clearly and succinctly transforming a callback into a promise:

let result = await new Promise((resolve, reject) => {
  someOldFunc(..., (error, data) => error ? reject(error) : resolve(data));
});

But even still, the ternary operator does not pass the Crockford test.

"If a feature is sometimes dangerous, and there is a better option, then always use the better option."

 

You could still do that without the ternary and in the same space:

error && reject(error) || resolve(data)
 

No, just... no.
The ternary operator is better than logical operator abuse.

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).

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.

code of conduct - report abuse