Blog & News

The Ternary Operator in Flash (if-else shorthand)

girl learning coding in front of computer

Most people fluent in Flash Actionscript are familiar with unary and binary operators, but there is also a ternary operator that can be quite useful. First, a refresh on operators:

Unary: count++;

Binary: count = count * 2;

Ternary: var result:String = (count == 0) ? “Empty” : “Not Empty”);

So what does this mean? You can use the ternary form of the if statement as a shorthand. Let’s look at the equivalent full if-else statement:

var result:String;
if (count == 0) result = “Empty”;
else result = “Not Empty”;

Of course, using the ternary operator cuts down on code readability, but three lines can effectively be cut down to one. Remember, the form is this:

(condition) ? ifTrueDoThis : ifFalseDoThis;