DEV Community

JavaScript Ternary Operator

Tim Apple on October 30, 2019

In my learning of 'Control Flow' in JavaScript I ran into the Ternary Operator (or Condtional Operator). I find these to be just to cool not to wri...
Collapse
 
travisvalenti profile image
Travis Valenti • Edited

There's nothing more beautiful than a well executed ternary expression.

It becomes especially useful when working with templates where you want a simple inline way of switching between behaviors or components.

If you'd like some more things to look into, thing about what happens when you use logical operators (&&, ||) to determine what parts of code run (also super useful when templating, but also for providing defaults like const x = someParameter || 'defaultString').

Collapse
 
l2aelba profile image
l2aelba • Edited

I would do something like this…

let message = condition ? 'result' : 'default'
console.log(message)

Why? : Think about if you not just console.log or do async functions

Collapse
 
heytimapple profile image
Tim Apple

That's very cool, I'm still learning my way around myself so i'm pretty positive I haven't come close to wrapping my mind around all the possibilities.