Table of Contents

7.3 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 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 try again.";
  this.gotoAndStop("loginError");
} else {
  this.gotoAndPlay("intro");
}

Note that an else if statement is merely a combination of an else statement 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 than y");
} else {
  trace("x and y are equal");
}
// Expanded Nested if/else chain
if (x > y) {
  trace("x is larger than y");
} else {
  if (x < y) {
    trace("x is smaller than y");
  } else {
    trace("x and y are equal");
  }
}

Table of Contents