Cofounded Host Collective (DiscountASP.net). Cofounded Player Axis (Social Gaming). Computer Scientist and Technology Evangelist with 20+ years of experience with JavaScript!
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:
constfoo=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.
Sasa is a highly driven full stack software developer with background in finance and accounting. A relentless problem solver who is passionate about finding elegant solutions to problems at hand.
Sasa is a highly driven full stack software developer with background in finance and accounting. A relentless problem solver who is passionate about finding elegant solutions to problems at hand.
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.
☝️ This statement can be proven false with this block of code:
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.Just because you can do something does not mean you should, have fun maintaining your library :)
Just because you shouldn't do something it doesn't mean you can't ;)
True as well :D