Tip 18 | Check Data Quickly with the Ternary Operator |
In this tip, youâll learn how to avoid reassignment with the ternary operator.
By now, you may have noticed that I love simple code. Iâll always try to get an expression reduced down to the fewest characters I can. I blame a former coworker who reviewed some code I wrote at one of my first jobs.
â | âifâ(active) { |
â | âvarâ display = â'bold'â |
â | } âelseâ { |
â | âvarâ display = â'normal'â |
â | } |
He took one glance and casually said, âYou should just make that a ternary.â
âOf course,â I agreed, not quite sure what he was talking about. After looking it up, I simplified the code to a one-line expression and my code has never been the same.
â | âvarâ display ... |
Get Simplifying JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.