DEV Community

Cover image for Thinking about Ternary Operators
commdao
commdao

Posted on

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

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy πŸŽ–οΈ

You're actually referring to the 'conditional' operator - which just happens to be a ternary operator. A ternary operator is simply an operator that has 3 operands. Similarly, a binary operator has two operands - and a unary operator has one

Collapse
 
commdao profile image
commdao

Oh, thanks for clearing that up-- makes sense!!