DEV Community

loading...

Discussion on: What do you think about the ternary operator?

Collapse
jvarness profile image
Jake Varness

Absolutely love it for it's simplicity and how widely it's been implemented in almost every programming language.

But I absolutely cannot stand it when someone does something like this:

return expressionThatReturnsBoolean() ? true : false;

or this:

return !expressionThatReturnsBoolean() ? true : false;

or any variation of taking an expression that returns a boolean and immediately transforming that boolean with a ternary operator to return a boolean.

I've had many people tell me that this improves the "readability" of the statement, but I strongly disagree. I think all it does is add redundancy to the code and add more complexity with little benefit.

Collapse
shreyasminocha profile image
Shreyas Minocha Author

I agree with you on return expressionThatReturnsBoolean() ? true : false;. Readability can be subjective though ¯\(ツ)/¯.

Collapse
jvarness profile image
Jake Varness

Readability is subjective, but I would say that when your code reads: if true return true, if false return false... I mean you might as well be writing:

if (expressionThatReturnsBoolean() == true) {
  return true;
}
else {
  return false;
}
Thread Thread
shreyasminocha profile image
Shreyas Minocha Author

Perhaps.

Readability is also contextual. I might do similar things in two different ways depending on how readable it would be over there. Doing it your way might be my preference, but sometimes I'll find myself using a ternary for the same.