Ternary / Conditional Operator in Actionscript 3

Like in many programming languages, Actionscript 3 allows for use of the ternary operator ?:

Let’s take a normal if statement as an example:

1
2
3
4
5
6
7
8
if( score == 10)
{
    win = true;
}
else
{
    win = false;   
}

This could be written in a different way using the ternary operator:

1
win = (score == 10) ? true : false;

So the syntax is: Expression ? statement : statement

If the expression is true, the value of the first statement is returned. Otherwise the value of the 2nd statement is returned.

Use the ternary operator judiciously. I’d recommend using it only with simple expressions and avoid nesting. This can make code very difficult to read!

Although I don’t like nesting, I think that chaining is not too bad if used to make the code easier to read. Here is an example of how the ternary operator can be used to make the code less noisy and more compact:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
x = (height < 100) ? "Short" :
    (height < 200) ? "Average" :
    (height < 300) ? "Tall" :
    (height < 400) ? "Giant";
   
// The above is equivalent to the following if/else chain

if (height < 100)
{
    x = "Short";
}
else if (height < 200)
{
    x = "Average";
}
else if (height < 300)
{
    x = "Tall";
}
else
{
    x = "Giant";
}

To be fair, I could have written each of those if/else statements on one line each, but I still feel like the ternary version is cleaner. Of course, it is completely up to you where and when you use it. Enjoy!

Share on FacebookShare on Google+Share on StumbleUponTweet about this on TwitterEmail this to someone

Facebook comments:

Leave a Reply