DEV Community

Discussion on: A simple tip for cleaner code

Collapse
 
joelnet profile image
JavaScript Joel

Yes your example was a simple one, though simplicity is not a factor as any program can be expressed as a single expression, regardless of the simplicity. Therefore any example can be converted into a conditional ternary. Though it may is possible not look the cleanest or be the best solution.

But if we have code between the condition and the return statement, you cannot use a ternary oh enlightened one ;)

☝️ This statement can be proven false with this block of code:

const foo = bar =>
  bar > 0 ? (
    console.log('Execute some code here for YES'),
    'YES'
  ) : bar === 0 ? (
    console.log('Execute some code here for MAYBE'),
    'MAYBE'
  ) : (
    console.log('Execute some code here for NO'),
    'NO'
  )

To demonstrate my point that you can write any application as a single expression, you can read my article where I have written a fully functional Promise library, a fairly complex program, as a single function expression. dev.to/joelnet/challenge-program-w...

The good thing about using a ternary operator is that when the operator becomes complicated, it is a signal that your function needs to be broken down into smaller pieces. Where as with the if statement, you can easily add too many statements without receiving this signal and end up with a function that breaks the Single Responsibility rule.

  • The Enlightened One

mic drop

Thread Thread
 
blackcat_dev profile image
Sasha Blagojevic • Edited

Just because you can do something does not mean you should, have fun maintaining your library :)

Thread Thread
 
aramix profile image
Aram Bayadyan

Just because you shouldn't do something it doesn't mean you can't ;)

Thread Thread
 
blackcat_dev profile image
Sasha Blagojevic

True as well :D