The else if Statement
Using
if
and
else
, we can optionally execute one of two code
blocks. By using if
and else
if
, we can optionally execute one (or even none) of an
unlimited number of code blocks. Like
else
, else if
is a
syntactic extension of an if
statement:
if (condition1
) {substatements1
} else if (condition2
) {substatements2
} else if (condition3
) {substatements3
} else {substatements4
// Catchall if other conditions were not met }
where condition1
,
condition2
, and
condition3
must be valid expressions.
substatements1
will be executed if
condition1
is true
. If
condition1
is false
,
substatements2
will be executed if
condition2
is true
.
Otherwise, condition3
is evaluated and so
on for as many else if
statements are provided.
If none of the test expressions are true
, the
statements in the final catchall else
clause
will be executed. For example, we could write a login-checking
routine to provide insightful error messages, like this:
if (userName != validUser) { message = "User not found. Please try again."; gotoAndStop("loginError"); } else if (password != correctPassword) { message = "Password incorrect. Please try again."; gotoAndStop("loginError"); } else { gotoAndPlay("intro"); }
Note that an else if
statement is merely a
combination of an else
with a nested
if
statement. Although the following two code
segments are equivalent, the first one is much easier to read:
// Normal "else if" syntax if (x > y) { trace("x is larger than y"); } else if (x < y) { trace("x is smaller ...
Get ActionScript: The Definitive Guide 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.