152 Syntax and Language Fundamentals
About the conditional operator and alternative syntax
If you like shortcuts, you can use the conditional (?:) operator, also called conditional
expressions. The conditional operator lets you convert simple
if..else statements into a
single line of code. The operator helps decrease the amount of code you write while
accomplishing the same thing, but it also tends to make your ActionScript more difficult
to read.
The following condition is written in long hand, and checks whether the variable
numTwo is
greater than zero, and returns the result of
numOne/numTwo or a string of carrot:
var numOne:Number = 8;
var numTwo:Number = 5;
if (numTwo > 0) {
trace(numOne / numTwo); // 1.6
} else {
trace("carrot");
}
Using a conditional expression, you would write the same code using this format:
var numOne:Number = 8;
var numTwo:Number = 0;
trace((numTwo > 0) ? numOne/numTwo : "carrot");
As you can see, the shortened syntax reduces readability, and so it is not preferable. If you
must use conditional operators, place the leading condition (before the question mark [
?])
inside parentheses. This helps improve the readability of your ActionScript. The following
code is an example of ActionScript with improved readability:
var numOne:Number;
(numOne >= 5) ? numOne : -numOne;
You can write a conditional statement that returns a Boolean value, as the following
example shows:
if (cartArr.length > 0) {
return true;
} else {
return false;
}
However, compared with the previous code, the ActionScript in the following example
is preferable:
return (cartArr.length > 0);
The second snippet is shorter and has fewer expressions to evaluate. It’s easier to read
and understand.