Episode 14 of 46

Else If Statement in JavaScript

Deep dive into else if chains and the switch statement for handling multiple conditions.

When you have multiple conditions to check, else if lets you chain them together. For many fixed values, switch is a cleaner alternative.

Else If Chains

let day = "Monday";

if (day === "Monday") {
    console.log("Start of the week!");
} else if (day === "Friday") {
    console.log("Almost weekend!");
} else if (day === "Saturday" || day === "Sunday") {
    console.log("It's the weekend!");
} else {
    console.log("It's a regular weekday.");
}

The Switch Statement

When comparing one value against many options, switch is cleaner:

let fruit = "apple";

switch (fruit) {
    case "apple":
        console.log("Apples are $1.50/kg");
        break;
    case "banana":
        console.log("Bananas are $1.00/kg");
        break;
    case "orange":
        console.log("Oranges are $2.00/kg");
        break;
    default:
        console.log("We don't have that fruit.");
}

Important: The break Keyword

Without break, execution "falls through" to the next case:

let grade = "B";

switch (grade) {
    case "A":
    case "B":
        console.log("Good job!");  // Both A and B reach here
        break;
    case "C":
        console.log("You passed.");
        break;
    default:
        console.log("Try harder.");
}

When to Use Which

  • if/else if — for ranges and complex conditions
  • switch — for comparing one variable against fixed values