Loading...

Section

Expanding Choices: The 'Else If' Statement

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

So far, we've seen how if statements let us make a single decision, and if-else statements let us choose between two paths. But what if our program needs to consider more than just two possibilities? This is where the else if statement shines. Think of it as adding more 'what ifs' to our decision-making process. It allows us to chain multiple conditions together, and only the first one that evaluates to true will have its corresponding code block executed. If none of the if or else if conditions are true, then the optional else block (if present) will be executed.

Let's illustrate this with an example. Imagine you're writing a program to determine a student's grade based on their score. A simple if-else wouldn't be enough to cover all the possible letter grades (A, B, C, D, F). We need to check a range of scores for each grade.

let score = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 80) {
  console.log("Grade: B");
} else if (score >= 70) {
  console.log("Grade: C");
} else if (score >= 60) {
  console.log("Grade: D");
} else {
  console.log("Grade: F");
}

In this example:

  • The program first checks if score is 90 or above. If it is, 'Grade: A' is printed, and the rest of the conditions are skipped.
  • If score is not 90 or above, it then checks if score is 80 or above. If true, 'Grade: B' is printed, and the subsequent conditions are ignored.
  • This continues for each else if condition.
  • If none of the if or else if conditions are met (meaning the score is below 60), the else block is executed, printing 'Grade: F'.
graph TD;
    A{Score >= 90?};
    B{Score >= 80?};
    C{Score >= 70?};
    D{Score >= 60?};
    E[Grade: A];
    F[Grade: B];
    G[Grade: C];
    H[Grade: D];
    I[Grade: F];

    A -- Yes --> E;
    A -- No --> B;
    B -- Yes --> F;
    B -- No --> C;
    C -- Yes --> G;
    C -- No --> D;
    D -- Yes --> H;
    D -- No --> I;

The beauty of else if is that it creates a mutually exclusive set of conditions. Once a condition is met and its code executed, the rest of the else if and else blocks are bypassed. This ensures that only one outcome is chosen from the series of checks, making your program's logic predictable and efficient.