JavaScript Ternary Operator
Tim Apple

Tim Apple @heytimapple

About: Clickity,clack!

Location:
Staten Island, NY
Joined:
May 17, 2019

JavaScript Ternary Operator

Publish Date: Oct 30 '19
9 3

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 write a little about them.

The Ternary Operator is a real short way to choose between two things instead of using if/else. They a basically structured as:

condition ? if true : if false; The ? is your operator.
So lets do an example.

if (cheese === 'Yellow') {
 console.log("Got me some yellow cheese!");
 } else {
 console.log("Got me some moldy cheese!");
 } 
Enter fullscreen mode Exit fullscreen mode

So doing the above if/else the "Ternary way" would look more like this.

cheese === "Yellow" ? console.log("Got me some yellow cheese!") : console.log("Got me some moldy cheese!");

  • So we have our condition - cheese === "Yellow"
  • Our True - console.log("Got me some yellow cheese!")
  • And our False = console.log("Got me some moldy cheese!")

I don't know why I love this so much. Well I do, it just makes things a bit simpler in my eyes. So give them a go if you haven't before. They are pretty fun.

Cheers!

Comments 3 total

  • Travis Valenti
    Travis ValentiOct 30, 2019

    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').

  • l2aelba
    l2aelbaOct 30, 2019

    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

    • Tim Apple
      Tim AppleOct 30, 2019

      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.

Add comment