Thinking about Ternary Operators

commdao

commdao

Posted on June 30, 2021

Thinking about Ternary Operators

This is sort of a more advanced topic, and I've been recommended not to worry about it too much. After all, you want to feel more comfortable with the basics before you simplify, and "simplification" can be a never-ending process.

That said, I know myself, and it's something I want to duck talk through so I can get back to the more important basics.

Drinking Age

First, let me review a more traditional if / else statement:

var age = 22;
var canDrink;
     if (age > 21) {
          canDrink = 'yes';
     } else {
          canDrink = 'no';
     }
Enter fullscreen mode Exit fullscreen mode

If someone is over 21, they can drink. If they're under, they can't. In this case we have someone who is 22, so they'll be okay.

Ternary Operators follow that logic too, but it manifests like this:

condition ? expression_1 : expression_2;

So using that drinking example:

var age = 22;
var canDrink = age > 21 ? 'yes' : 'no';
Enter fullscreen mode Exit fullscreen mode

Makes sense, right? Let's try with one more example.

Higher Salary Justifies Gaming Purchase

Let's say I want to make a certain salary before I can justify buying a PlayStation 5. (Honestly, we need some actual good console-exclusive games first, but bear with me here.)

I tell myself that I can't justify buying a PS5 unless I make $70,000, and what if I make minimum wage?

var salary = 28000
var buyPlaystation = salary > 70000 ? 'yes' : 'no';
Enter fullscreen mode Exit fullscreen mode

And one more time more traditionally:

var salary = 28000
var buyPlaystation;
     if (salary > 70000) {
          buyPlaystation = 'yes';
     } else {
          buyPlaystation = 'no';
     }
Enter fullscreen mode Exit fullscreen mode

It can get even more mileage and usage than that, but this is a good digest for me now.


Photo by https://photostockeditor.com

💖 💪 🙅 🚩
commdao
commdao

Posted on June 30, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Thinking about Ternary Operators
functional Thinking about Ternary Operators

June 30, 2021