joshbuhler.com

Using the Ternary Operator

by Josh on Jul.07, 2005, under ActionScript, Development, Flash

Just a quick mini-tutorial on using the ternary operator in ActionScript. One of those things that shows up in my search logs, so the next time someone searches for it, they should be able to find it.

The ActionScript Ternary Operator

The ternary operator, "? :", is basically a shorcut for writing quick conditional statements that evaluate to either true or false. Similar to an if/else statement, you use them to make a decision in your code, and act based on that decision.

Here's the syntax:

  1. // using the ternary operator
  2. (condition) ? isTrueAction : isFalseAction;
  3.  

The ( ) around condition are optional, however they do help to clearly illustrate the condition. The code above is the same as writing:

  1. // the same thing, only more typing
  2. if (condition) {
  3.         isTrueAction;
  4. } else {
  5.         isFalseAction;
  6. }
  7.  

Now, you won't be able to use this for something that has multiple statements after the condition like you can in an if statement, but it does have it's uses for quick little things. For example, you couldn't use it for something like this:

  1. // this can't be written out using ternary operators
  2. if (condition) {
  3.         isTrueAction;
  4.         var bob:String = "something";
  5.         goDoSomethingNow();
  6. } else {
  7.         isFalseAction;
  8. }
  9.  

But it's great for something like this:

  1. // this is a great use for ternary operators
  2. (superBowlWon == true) ? gotoDisneyland() : goHome();
  3.  

Or even for checking if a number is even or not.

You can also use this technique to set values for variables:

  1. // setting a variable like this...
  2. var pillToTake:String = (stayInMatrix == true) ? "blue" : "red";
  3. //
  4. // is the same as doing this:
  5. if (stayInMatrix == true) {
  6.         var pillToTake:String = "blue";
  7. } else {
  8.         var pillToTake:String = "red";
  9. }
  10.  

So, as you can see, using this operator can save you time by requiring less typing in a few situations. Now, it's not the solution to everything, but as you start using it more, you'll start to wonder how you worked without it. (Maybe not, but it'll make me feel better if I can imagine that I've somehow improved your life.)

Also, after I finished writing this, I decided I wanted to try and determine which method is faster, to see if there's another argument for learning how to use this stuff. So in a pretty informal, and un-scientific way, I ran the following test:

  1. // testing ternary operator vs. if/else
  2. // just copy and paste onto the main timeline, and run
  3. //
  4. var loops:Number = 10000;
  5. //
  6. // ternary test
  7. var startTime1:Number = getTimer();
  8. for (var i:Number = 0; i < loops; i++) {
  9.         var testNum:Number = Math.floor(Math.random() * 100);
  10.         var isEven:Boolean = ((testNum % 2) == 0) ? true : false;
  11. }
  12. var endTime1:Number = getTimer();
  13. var totalTime1:Number = endTime1 - startTime1;
  14. //
  15. // if/else test
  16. var startTime2:Number = getTimer();
  17. for (var i:Number = 0; i < loops; i++) {
  18.         var testNum:Number = Math.floor(Math.random() * 100);
  19.         if ((testNum % 2) == 0) {
  20.                 var isEven:Boolean = true;
  21.         } else {
  22.                 var isEven:Boolean = false;
  23.         }
  24. }
  25. var endTime2:Number = getTimer();
  26. var totalTime2:Number = endTime2 - startTime2;
  27. //
  28. trace("Total Times: \n");
  29. trace("\tTernary: " + totalTime1);
  30. trace("\tif/else: " + totalTime2);
  31.  

Running this test on my PowerMac with dual G5 2.0, and 1 GB ram, I came up with the following averages after running it 20-30 times: Ternary: 201 ms, if/else: 195 ms. Now, your results may vary, and this most likely isn't the best way to test something like this, but it's enough for me to see that there is a speed difference, but it's not enough of a difference to really make me stick to if/else exclusively.



:, , , ,
3 comments for this entry:
  1. Clayton Graham

    An excellent little tutorial. Many thanks!

  2. Matthew Bergsma

    Interesting - on a dual 2.5 g5, I averaged about these numbers compiling with mtasc: Ternary: 79 if/else: 76, But IF I changed the order of which for loops run first (run the if/else one before the ternary one) the results Swap! Ternary: 76, if/else: 79.

    So it looks like there might not be a performance hit at all for using ternary syntax -

  3. Samuel

    can someone explains what is the logic of:

    (cond) ? (cond) ? 1 : 2 : 3

    thanks

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...