Blog

The ternary

If you’ve been doing PHP or Javascript programming, and you’ve never used the ternary operator then you’re in for a treat.

But if you have used it before, I think I have a tip that will help when using it.

Here it is:

var x = (expression) ? result1 : result2;

Now, what does that say?

Basically, it’s for when you’re assigning variables, you can evaluate an expression, and depending on the result, it will give you multiple results.

It’s basically equivalent to this:

var x;
if (expression) {
    x = result1;
} else {
    x = result2;
}

So obviously, you can see the benefit of doing it all on one line.

Now, however, many people’s complaint is that it leads to highly unreadable code. However, it’s still really cool. So what I’ve done is try to come up with a way that combines legibility with code convenience.

Basically, here it is:

var x = (expression)
            ? result1
            : result2;
       
So, you see by putting the ? and the : on the same alignment with the expression, you have a much more legible expression, without the extra code.

As a side note, you can also do multiple expressions, though, in general, if you start getting that crazy, an if/else/if or a switch are both easier to maintain long term for highly complex expressions.
Here’s how you’d do multiple expressions:

var x = (expression1)
            ? result1
            : (expression2)
               ? result2_1
               : result2_2;
           
Enjoi!

2 comments to “The ternary”

  1. Ryan Miglavs
    01

    Cool! I get it, now. I've seen that operator around and vaguely understood "it's something about if/else", but now I see how it works.

    And I like your notation for it as well.

    Thanks.

  2. Nate Cavanaugh
    02

    Awesome, I’m glad I could help explain it :)

Comments are closed.