Start learning free

LESSON 86 OF 348 · CONDITIONAL STATEMENTS

Chaining Conditionals in TypeScript: else if

Lesson Read the full explanation

Sometimes we can have more than two possible scenarios which need a different code to be ran. We can add else if statements to allow for as many outcomes as we want:

let language = "Python";
if(language == "JavaScript") {
    console.log("It's super popular!");
}
else if(language == "Python") {
    console.log("It's so simple!");
}
else if (language == "Java") {
    console.log("It's pretty hardcore!");
}
else {
    console.log("It's exotic!");
}

In the example above, language == "JavaScript" evaluates to false, so we move on and enter the following else if.

There, language == "Python" evaluates to true, so we execute what's inside that block and print "It's so simple!".

The rest of the conditions are not evaluated.

In case none of the conditions evaluates to true, then the code in the final else statement would execute. For example, if language was "Go", the program would have printed "It's exotic!"


Assignment
Follow the Coding Tutorial and let's write some chained conditionals.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · CONDITIONAL STATEMENTS

    Chaining Conditionals in TypeScript, explained

    What a chain of conditionals is

    An if/else pair chooses between two outcomes. Many decisions have more than two: a grade can be failing, passing, good or perfect. TypeScript handles this by inserting any number of else if branches between the if and the final else. The whole thing is one statement, called a chain.

    The rule is simple. The conditions are tested from top to bottom. The first one that is true has its block run, and the rest of the chain is skipped without being evaluated. If none is true, the final else runs. The else is optional, and if you leave it out and no condition matches, nothing happens.

    Syntax

    let language: string = "Python";
    if (language == "JavaScript") {
        console.log("It's super popular!");
    } else if (language == "Python") {
        console.log("It's so simple!");
    } else if (language == "Java") {
        console.log("It's pretty hardcore!");
    } else {
        console.log("It's exotic!");
    }
    

    This prints It's so simple!. The first condition is false, so the chain moves on. The second is true, so its block runs, and the Java check is never evaluated. Set language to "Go" and every condition is false, so the final else prints It's exotic!.

    Write the braces even when a block holds one line. The language allows leaving them out, but a second line added later is then easy to misplace.

    Order matters

    Because only the first true branch runs, the order of the branches is part of the logic. Each branch can rely on every earlier condition having been false. That lets you write ranges with only one bound:

    function check(n: number): void {
        if (n > 0) {
            console.log("first");
        } else if (n > 10) {
            console.log("never");
        } else {
            console.log("other");
        }
    }
    check(20);
    check(-1);
    
    first
    other
    

    Here n > 10 can never be reached with a true result: any number above 10 is also above 0, so the first branch already caught it. When a branch seems to be ignored, check whether an earlier, broader condition is catching its values. Put the most specific condition first.

    A chain is not a series of separate ifs

    Compare the chain with separate if statements:

    let g2: number = 4;
    if (g2 < 5) console.log("fail");
    if (g2 <= 7) console.log("pass");
    
    fail
    pass
    

    Each if here is tested on its own, so both messages print. Joined with else if, only the first would. Use a chain when the outcomes are mutually exclusive.

    Gotchas in TypeScript

    • Prefer === to ==. The loose == converts types before comparing, so the number 5 and the string "5" count as equal. === compares without converting. TypeScript's type checker also catches many such comparisons at compile time, but the types are erased in the generated JavaScript, so === is the safer habit.
    • Write else if as two words. There is no elseif keyword.
    • A stray semicolon ends the statement. if (x > 3); followed by a block makes the block run unconditionally.
    • Don't forget the final else when you need a fallback. Without it, values outside every range produce no output at all.

    The lesson's exercise

    The code starts with let grade: number = 8; and the task is to print a message for each range of grades. Build the chain one branch at a time.

    1. Start with the failing case. An if checks grade < 5 and logs "Failed the test". Handling the lowest grades first lets every later branch assume the grade is at least 5.
    2. Add an else if for grade <= 7. It logs "Passed the test". The comparison is "less than or equal" because 7 itself belongs here. There is no lower bound to write, since grades below 5 were already caught.
    3. Add one more else if for grade <= 9. It logs "Good Job", again with no lower bound.
    4. Close the chain with else. It has no condition. It logs "Perfect" for everything above 9.
    let grade: number = 8;
    
    if (grade < 5) {
        console.log("Failed the test");
    } else if (grade <= 7) {
        console.log("Passed the test");
    } else if (grade <= 9) {
        console.log("Good Job");
    } else {
        console.log("Perfect");
    }
    

    With grade equal to 8, the first two conditions are false and the third is true, so the output is Good Job. Try the values 4, 7, 9 and 10 in the editor above: they print Failed the test, Passed the test, Good Job and Perfect. The boundary values 7 and 9 are the ones worth checking, because they test the <= comparisons.

    Key takeaways

    • A chain tests its conditions from top to bottom and runs only the first block whose condition is true.
    • Later branches can rely on the earlier conditions being false, so they need only one bound.
    • Put the most specific conditions first, and finish with an else for everything else.
    • Separate if statements are independent. Only else if makes the outcomes exclusive.
    • Use === for comparisons, and decide boundary values (< or <=) deliberately.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free