
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
The else if Statement
|
159
which is equivalent to:
var guess = "c";
var answer = "d";
if (guess = = answer) {
response = "Right";
} else {
response = "Wrong";
}
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.Ifcondition1 is false,
substatements2 will be executed if condition2 is true. Otherwise, condition3 is evalu-
ated, and the process continues 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.";
this.gotoAndStop("loginError");
} else if (password != correctPassword) {
message = "Password incorrect. Please ...