Lesser Known Operators:  Conditional (?:)

ActionScript 2.0

Operators are elements in a programming language that combine, compare, or change values in an expression.  Common operators, such as < (less than) and > (greater than) are familiar to most developers.  Those, for example, are relational operators; they compare two values and return a Boolean (true or false) that describes the relationship between them (A is greater than B or it isn’t).  Other common relational examples include <= (less than or equal to) and >= (greater than or equal to).

Of the various categories of operators — relational is one of many — there are a handful that are undeniably lesser known.  One of those is the conditional operator (?:), so let’s take a look at what it has to offer. 

What it is

The conditional operator (?:) is a ternary operator; this is, it deals with three operands.  In simple terms, it evaluates one expression (the first operand) as true or false; if true, it returns the second operand; if false, it returns the third.  Let’s see it in action.

For sake of illustration, we’ll use a combination of Math.round() and Math.random() to virtually “flip a coin.”  Math.random() generates a non-integer between zero and one, and Math.round() shoves that non-integer toward either extreme; in other words, the result will either be zero or one, which corresponds to false or true, respectively.  This expression will be our first operand.

Math.round(Math.random())

Operands two and three will be a pair of strings, “heads” and “tails.”  The first operand goes between a pair of parentheses (()), the second follows a question mark (?), and the third follows a colon (:).  In context, then, the three operands appear like this:

(Math.round(Math.random())) ? "heads" : "tails";

So, for example, if you had a variable, outcome, that needed to say either “heads” or “tails,” you could set that variable as follows:

var outcome:String = (Math.round(Math.random())) ? "heads" : "tails";

That looks awfully familiar

In essence, the conditional operator provides the same result as an if/else statement.  Compare the above with this:

var outcome:String;
  if (Math.round(Math.random())) {
   outcome = "heads";
  } else {
   outcome = "tails";
  }

Why choose one over the other?  Well heck, the version with the conditional operator requires fewer keystrokes.  ;)

Personally, I often use this approach to initialize variables that require a default value.  Normally, of course, you would simply set the default value in the declaration …

var luckyNumber:Number = 11;

… but sometimes requirements dictate that the value be supplied by the user.  In such cases (and surely others), you simply can’t rely on the user actually doing what’s expected.  So you cover your bases.

In ActionScript 1.0 and 2.0, variables are assessed as undefined when they haven’t yet been given a value.  The undefined constant happens to correspond to false.  In situations where undefined is not acceptable, the conditional operator provides an uncluttered way to assign a default value.

luckyNumber = (luckyNumber) ? luckyNumber : 11;

Looks repetitive, right?  More repetitive than necessary.  (Gosh, you can say that again!)

In the above, the variable luckyNumber is evaluated inside the parentheses of the conditional operator’s first operand.  If luckyNumber is not undefined — that is, if it happens to already have a value assigned to it — then it evaluates as true and the second operand’s value is passed back to luckyNumber.  Of course, the second operand is luckyNumber, so all this rigamarole is simply another way of saying, “Hey, if luckyNumber already has a value, then leave it as it is.”  On the other hand, if luckyNumber is undefined (has no value yet), the first operand evaluates to false, and the third operand is passed back.  In other words, “If luckyNumber is undefined, make it 11.”

All that, in one crisp line.  Geeks find this sort of thing beautiful, and I count myself among them.

P.S.  I’m a strong advocate of the ActionScript 2.0 Language Reference and often encourage people to head there first.  The thing about operators is that they’re usually just punctuation marks, which makes them a bit tougher to locate.  Best bet:  just search the word “operators” — you’ll see the whole list.

2 Responses to “Lesser Known Operators:  Conditional (?:)”

  1. myIP Says:

    BUG NOTICE: I was trying to find the article titled “Lesser Known Operators: Conditional (?:)” and had a hard time at it. If a user clicks on “July 2006” link in the archive section it will not appear. However if the user clicks on “ActionScript 2.0” link in the categories section it will appear. Perhaps it conflicts with the other article you have for July 11?
    Anyways, I really enjoy reading your articles. Hey, I am still your “livedocs go-to guy” right?

  2. David Stiller Says:

    myIP,

    Actually, July has more than one page of summaries; you have to click “Previous Entries” to see this one. My favorite approach is the Search, though. ;)

    I’m glad you like the articles! Have you checked the LiveDocs section for ActionScript 3.0 yet? Someone with your hawk eye could have a field day there …


    http://livedocs.macromedia.com/labs/as3preview/langref/

Leave a Reply