You often need your ActionScript code to make decisions, such as
whether to execute a particular action or group of actions. To
execute an action under certain circumstances, use one of
ActionScript’s conditional
statements: if
, switch
, or
the ternary conditional operator (?
:).
The conditional statements allow you to make logical decisions, and
you’ll learn from experience which is more
appropriate for a given situation. The if
statement is most appropriate when you want to tell your Flash movie
to do something only when a certain condition is met (i.e., when the
condition is true). When you have several possible conditions to
test, you can use the switch
statement instead.
And you can use Flash’s ternary conditional operator
to perform conditional checking and assignment on a single line.
First, we’ll look at the if
statement. Of the conditional statements in ActionScript, the
if
statement is the most important to
understand. In its most basic form, an if
statement includes the keyword if
followed by the
test expression whose truthfulness you want to evaluate to determine
which action or actions to execute. The test expression must be in
parentheses, and the statement(s) to be executed should be within
curly braces (the latter is mandatory if there is more than one
statement in the statement block).
Here, we check whether animalName
contains the
word “turtle”. This might be used
to check whether the user answered a quiz question correctly (here,
animalName
is a variable assumed to contain the
user’s answer). Note that the double equals sign
(==
) is used to test whether two items are equal.
It should not be confused with the single equals sign
(=
), which is used to assign a value to an item.
if (animalName == "turtle") { // Thistrace( )
statement executes only whenanimalName
is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); }
Additionally, you can add an else
clause to an
if
statement to perform alternative actions if
the condition is false. Note that the trace( )
command has no effect when the Flash movie is running
in a
browser, so it is intended for testing purposes only. We use the
gotoAndStop( )
command to jump to a different
frame (presumably one that displays an appropriate message) depending
on whether the user answered the question correctly or incorrectly.
if (animalName == "turtle") { // These statements execute only whenanimalName
is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); gotoAndStop("CongratulationsScreen"); } else { // These statements execute only whenanimalName
is not equal to "turtle". trace("Sorry, you got the question wrong."); gotoAndStop("TryAgainScreen"); }
Tip
The gotoAndStop( )
command jumps to a frame with
the specified label or frame number and is used in this example to
illustrate typical real-world usage. The example assumes
you’ve created a Flash movie with frames labeled
“CongratulationsScreen” and
“TryAgainScreen.” To label a frame,
highlight one of the layers in the timeline and add a label using the
Frame field in the Property inspector.
You can add an else if
clause to an
if
statement. If the if
condition is true, the else if
clause is
skipped. If the if
condition is false, the
ActionScript interpreter checks to see if the else
if
condition is true.
if (animalName == "turtle") { // Thistrace( )
statement executes only whenanimalName
is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); } else if (animalName == "dove") { // Thistrace( )
statement executes only whenanimalName
is not "turtle" but is // "dove". trace("Sorry, a dove is a bird, not a reptile."); }
What if the preceding example was written as two separate
if
statements (one to check if
animalName
is
“turtle” and another to check if it
is “dove”)? The example would work
as intended, but it would be less efficient. Using the else
if
statement guarantees that if
animalName
is
“turtle”, we don’t
bother checking if it is also equal to
“dove”.
Tip
If your two conditions are mutually exclusive, use an else
if
clause to check the second condition. If your two
conditions are not mutually exclusive, and you want to perform both
statement blocks when both conditions are met, use two separate
if
statements.
When you use an if
statement
with both else if
and else
clauses, the else
clause must be the last clause in the statement. The final
else
clause is convenient as a catchall;
it’s where you can put statements that take the
appropriate action if none of the other conditions are met.
if (animalName == "turtle") { // Thistrace( )
statement executes only whenanimalName
is equal to "turtle". trace("Yay! 'Turtle' is the correct answer."); } else if (animalName == "dove") { // This statement executes only whenanimalName
is not "turtle" but is "dove". trace("Sorry, a dove is a bird, not a reptile."); } else { // This statement executes only whenanimalName
is neither "turtle" nor "dove". trace("Sorry, try again."); }
You can also include more than one else if
clause in an if
statement. However, in that
case, you should most likely use a switch
statement instead; generally, switch
statements
are more legible and succinct than the comparable
if
statement. Where performance is critical,
some ActionScripters prefer to use if
statements, which allow somewhat greater control for optimization
purposes.
A switch
statement is composed of three parts:
-
The
switch
keyword - Test expression
This is an expression, enclosed in parentheses, whose value you want to test in order to determine which actions to execute.
-
The
switch
statement body The statement body, enclosed in curly braces, is composed of
cases
. Each case is composed of the following parts:-
The
case
ordefault
keyword Each case must begin with a
case
keyword. The exception is the default case (analogous to anelse
clause in anif
statement), which uses thedefault
keyword.- Case expression
This is an expression whose value is compared to the
switch
statement’s test expression. If the two values are equal, the code in the case body is executed. The default case (the case that uses thedefault
keyword) does not need a case expression.- Case body
This is one or more statements, usually ending in a
break
statement, to be performed if thecase
is true.
-
The
The switch
keyword is always followed by the test
expression in parentheses. Then, the switch
statement body is enclosed in curly braces. There can be one or more
case
statements within the
switch
statement body. Each case (other than the
default case) starts with the case
keyword
followed by the case expression and a colon. The default case (if one
is included) starts with the default
keyword
followed by a colon. Therefore, the general form of a
switch
statement is:
switch (testExpression
) { casecaseExpression
: // case body casecaseExpression
: // case body default: // case body }
Here is an example. Note that once a case tests true, all the
remaining actions in all subsequent cases within the
switch
statement body also execute. This example
is most likely not what the programmer intended:
var animalName = "dove"; /* In the followingswitch
statement, the firsttrace( )
statement does not execute becauseanimalName
is not equal to "turtle". But both the second and thirdtrace( )
statements execute, because once the "dove" case tests true, all subsequent code is executed. */ switch (animalName) { case "turtle": trace("Yay! 'Turtle' is the correct answer."); case "dove": trace("Sorry, a dove is a bird, not a reptile."); default: trace("Sorry, try again."); }
Normally, you should use break
statements at the
end of each case body to exit the switch
statement after executing the actions under the matching case.
Tip
The break
statement terminates the current
switch
statement, preventing statements in
subsequent case bodies from being executed erroneously.
You don’t need to add a break
statement
to the end of the last
case
or default
clause,
since it is the end of the switch
statement
anyway:
var animalName = "dove";
// Now, only the second trace( )
statement executes.
switch (animalName) {
case "turtle":
trace("Yay! 'Turtle' is the correct answer.");
break;
case "dove":
trace("Sorry, a dove is a bird, not a reptile.");
break;
default:
trace("Sorry, try again.");
}
The switch
statement is especially useful when
you want to perform the same action for one of several matching
possibilities. Simply list multiple case expressions one after the
other. For example:
switch (animalName) { case "turtle": case "alligator": case "iguana": trace("Yay! You named a reptile."); break; case "dove": case "pigeon": case "cardinal": trace("Sorry, you specified a bird, not a reptile."); break; default: trace("Sorry, try again."); }
ActionScript also supports the ternary conditional operator
(?
:), which allows you to perform a conditional
test and an assignment statement on a single line. A
“ternary” operator requires three
operands, as opposed to the one or two operands required by unary and
binary operators. The first operand of the conditional operator is a
conditional expression that evaluates to true
or
false
. The second operand is the value to assign
to the variable if the condition is true, and the third operand is
the value to assign if the condition is false.
varName
= (conditional expression
) ?valueIfTrue
:valueIfFalse
;
One common use of the ternary operator is in assigning default values to variables in functions if a parameter value was omitted when calling the function. For example:
function myFunction (param) { var val = (param != undefined) ? param : "default value"; }
The preceding example can be written using an if
statement:
function myFunction (param) { var val; if (param != undefined) { val = param; } else { val = "default value"; } }
Either way is correct; however, the ternary operator requires fewer lines of code and executes faster.
Here is an example in which salutation
defaults to
“Hello” if no
greeting
was specified; otherwise,
salutation
is set to
greeting
’s value.
function welcome (greeting) { var salutation = (greeting != undefined) ? greeting: "Hello"; trace (salutation + " Sailor!") }
Here are some examples of the results:
welcome( ); // Displays: Hello Sailor! welcome("Ahoy"); // Displays: Ahoy Sailor!
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.