If /Else Shorthand with the Ternary Operator

I just came across this little shortcut and thought I’d share.

Short, conditional evaulations, such as this…

var work:String = 'monotonous';
if (work == 'monotonous') {
   activity = 'update blog';
} else {
   activity = 'continue working';
trace(activity); //outputs 'update blog'

…can be written using a conditional, aka ternary, operator (?:), like this:

var work:String = 'monotonous';
activity = (work == 'monotonous') ? 'update blog' : 'continue working';
trace(activity); //outputs 'update blog'

It can become quite a time saver and it condenses your code making it easier to read.


20 thoughts on “If /Else Shorthand with the Ternary Operator

  1. Yeah, that does save a lot of time.

    Welcome to the blogging world by the way Glenn. I am going to add your site to my blogroll, can you do the same for me (www.thewarp.org)? You should also think about submitting your site to MXNA, they will take you. It will give you a lot more traffic as well.

  2. Peter,
    Using the code from the post as an example, if you needed to set three default variables in the first frame of your movie you’d be reducing the number of lines from 15 to 3 by using the ternary operator. Personally, I find it easier to discern what’s going on in those 3 lines of code than the 15.

    And no, I’m not mad. I’m rabid.


  3. Peter is probably an AS2 guy I imagine. In the rest of the development world (and Flash now because of AS3), this is a very common shortcut used all over the place.

  4. this is obviously a way to make programming seem more complicated than it is. (maybe so you can get paid more?)
    when you read the code back in your head I bet you translate it into “if else” etc.. so why not just write it like that in the first place. makes it easier to understand and maintain. Your example is using it shorthand in its very basic form.
    One of my colleagues wrote this today:

    String inCareDuration = (paramsMap.containsKey(“cboCareDuration”) && !((String)paramsMap.get(“cboCareDuration”)).equals(“-“))
    ? (fdetails.getBeenInCare().equals(“1”))
    ? (String)paramsMap.get(“cboCareDuration”)
    : “”
    : “”;

    I nearly had to slap him, until he sent me this alternative:

    String inCareDuration = “”;
    if(paramsMap.containsKey(“cboCareDuration”) && !((String)paramsMap.get(“cboCareDuration”)).equals(“-“))
    inCareDuration = (String)paramsMap.get(“cboCareDuration”);

  5. @Peter:
    “this is obviously a way to make programming seem more complicated than it is. (maybe so you can get paid more?)”

    Yes you’ve hit the nail directly on the head there, Peter. Caught me red-handed! I shorten my code by using a well-known programming technique so I can get paid more. I didn’t think anybody would catch on to my secret but I obviously didn’t plan on someone with your insight and intellect stopping by and exposing my true motives.

  6. I’m quite happy to use ternary operations when it’s applicable, but I just wanted to add one thing to this discussion – in a lot of cases using a ternary operation in AS3 will result in a larger SWF size. It’ll actually result in more ActionScript Bytes in your final file, than if you had used the fully unrolled version.

    I have noticed this happen when comparing integers and booleans especially, but on Strings the ternary approach typically works out better. Personally I find the unrolled version significantly easier to read (because it flows like logical English), but when I need to be ultra compact I’ll pick based on end file size, and often unrolled wins that battle.

  7. I think Peter and the rabidGadfly both have very good points. Sometimes it’s hard to read, but sometimes if you can write 8 lines in 1 line and it’s simple enough to still be easy to read then everybody’s happy 🙂

  8. @Peter, shortcuts are good once you are familiar with them. You wrote “etc.” instead of “et cetera” saving you a few strokes, but you knew what it meant and so did we.

  9. Nothing like awakening an old thread:) When togglin stuff I love ternaries:

    cb.selected=(cb.selected) ? false : true;

    sets the checkbox to selected if it’s not, sets it to not selected if it is… ezpz.

  10. 1. ternary operations are harder to read. just like recursive functions, it cuts down on code but is harder to read, especially for people who have never seen your code before.
    2. ternarys are nice because they save space but as davey said they are bigger than non-ternary lines by several bytes, thereby increasing your swf size. if you pepper a big program with a lot of them, especially vital parts of it (like the graphics portion of a game engine), while you think using ternarys will increase performance, by over-using them what will end up happening is the reverse.
    3. lets not pick on people coming from as2. i love as3 but if you think as3 is any more of a real programming language than as2, you fail

  11. Is that because you can do the same in both? What defines a real programming language?

    I hated AS3 when I started but now I can’t even remember why. I was a real newbie when I was using 2 so I never really used OO.

    But I really would love to know what it makes this true.

    “i love as3 but if you think as3 is any more of a real programming language than as2, you fail”.

    I’m not being provocative, I’m really interested to know. Do I think it’s better because it’s stricter? I know I was taken in by the FP engine(virtual machine thingy) benchmarks that were thrown about when it first hit the scene, that’s the reason I changed to 3. Anything that runs quicker is better as long as you don’t lose functionality.

    And on topic, I agree that if the filesize is bigger, then the point is lost. Optimisation techniques are supposed to be just that, and coders can’t complain about longhand when these days everything gets autocompleted.

    Great post though, never knew any of this, not even the name for it – “Ternary operation”.

    Thanks rabidGadFly dude!

  12. @epic fail:
    1. Harder to read if you use them for complex evaluations. For simple evals, easier to read, in my opinion.

    2. Sure it’s good to keep your SWF size small but if you’re talking about a few bytes here and there, and your specs do not require keeping the size as small as possible, using ternaries is not going to add any significant bloat to the final app.

    3. Either an inflammatory statement intended to start a comment war, or ignorance from a programmer who’s reluctant to learn something new.


  13. Didn’t realise how old this was before I wrote the below:

    I agree with you rG, I think ternary operator can make code easier to read when it’s simple… especially because it can remove so many lines of source code.

    I just use 1 rule though; do not nest ternary operations.

  14. Whenever I need a quick reminder of what ternary syntax is, I always google “as3 ternary expressions” –which brings me here. (1st result) Thanks

    Oh and *love* the fact that the 2nd comment is “are your mad?”

  15. I’ve been coding flash now for 11 years, sure I can read the shorthands, but I personally don’t use them I think it’s lazy – its like using shorthand variable names like ‘t’, when it actually represents ‘territory’. I think coders should always consider that other coders may one day have to edit their code, and avoiding shorthand stuff definatley makes it easier to read and understand quicker.

    1. Hi Taz,

      Everyone has their preferences when it comes to coding. If writing a full “if…then” eval helps you understand code easier, then that’s the technique you should use.

      I don’t use nested ternary statements because they can be confusing to decipher, and very difficult to debug. However, for setting a variable based on a simple condition, I like using them. The syntax is used frequently by coders across many languages, and I think it’s neater and easy to understand.

      Your analogy that it’s like using one letter rather than a descriptive word as a variable name just isn’t accurate. A poorly named variable requires the developer to trace the variable back to it’s declaration, and possibly further, to figure out its purpose.

      A ternary statement requires no such effort. Most developers familiar with ActionScript should be able to look at a simple conditional ternary statement and understand the logic without leaving that one line of code. If not, then a simple Google search should pull up plenty of results that will explain it. And from that point on, they have themselves another tool in their toolbox.


  16. if you ever had to debug a programm you didnt write yourself and somebody is using a lot of ternary operators, or even chains em, you’ll realize its hardly a timesaver…

    1. I find it funny that there’s any argument at all over this common coding technique, let alone the never-ending battle that continues to play itself out here in the comments of a post I wrote over 5 years ago.

      That fact is, the more I’ve coded, the more I’ve seen the technique utilized. It was my job for 5 years to debug code that I didn’t write myself, and dealing with ternary conditionals was never a problem.

      Knowing an alternative coding technique can only help.

      var problem = ( ternary hater ) ? “yours” : null;

      Keep learning!

Comments are closed.