Start learning free

LESSON 73 OF 348 · CONDITIONAL STATEMENTS

If-else Statements in TypeScript: Choosing Between Two Paths

Lesson Read the full explanation

Many times in our life, not only we choose to do something if a condition is met, but also choose to do something different if that condition is not met. For example:

If I'm tired:
    I take a nap
Otherwise:
    I start coding

If-else Statements:

When a condition for an if statement is true, the block of code following it is executed. What about when that condition is false? Normally nothing would happen.

With an else statement, we can have an alternate block of code to be executed. For example:

let amTired = false;
if(amTired) {
    console.log("I take a nap");
}
else {
    console.log("I start coding");
}

The code above prints "I start coding" since the expression inside the if evaluates to false and so TypeScript will enter the else statement and execute the code inside it.

An else statement cannot exist without a corresponding if statement. This combination is refered to as an if-else statement.


Assignment
Follow the Coding Tutorial and let's practice with if-else statements!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    TYPESCRIPT · CONDITIONAL STATEMENTS

    If Else in TypeScript, explained

    Doing something when the condition is false

    An if statement runs its block when a condition is true. When the condition is false, the block is skipped and, by itself, nothing else happens. Often that isn't enough: you want one action when the condition holds and a different action when it doesn't.

    If I'm tired:
        I take a nap
    Otherwise:
        I start coding
    

    In TypeScript, the "otherwise" part is an else block attached to the if:

    let amTired: boolean = false;
    
    if (amTired) {
        console.log("I take a nap");
    } else {
        console.log("I start coding");
    }
    

    Since amTired is false, the program skips the first block and runs the one after else. It prints I start coding.

    The two blocks are mutually exclusive. Exactly one of them runs, never both and never neither. That is the difference between an if-else and two separate if statements: with separate ones, both conditions are tested independently, and you must make sure they don't overlap.

    An else has no condition of its own and can't appear without an if in front of it. It catches every case that the if did not.

    The exercise

    The starting code already has an if that handles the passing case:

    let passed: boolean = false;
    if (passed) {
        console.log("Passed the test");
    }
    

    Because passed is false, this program prints nothing. The goal is to make it report a result in that case too.

    1. Find the } that closes the if block. The else goes right after it, on the same line.
    2. Write else { to open the new block.
    3. Inside, call console.log("Failed the test");.
    4. Close the block with its own }.

    The finished code:

    let passed: boolean = false;
    if (passed) {
        console.log("Passed the test");
    } else {
        console.log("Failed the test");
    }
    

    It now prints Failed the test. If you change the first line to true, it prints Passed the test instead, and the else block is skipped.

    Formatting and syntax

    The lesson places } else { on one line, which is the most common style in TypeScript. Putting else on the next line also works, because whitespace between the closing brace and the keyword doesn't matter. What does matter is that the braces match up: every opening { needs a closing }, and the else must come directly after the closing brace of the if block. If another statement sits in between, the if has already ended and the else is an error.

    A block can hold as many statements as you like. All of them belong to that branch, and the other branch's statements are skipped together. Both branches can also be longer than one line, so the structure scales from a single message to a whole piece of logic.

    Gotchas

    • Putting a condition after else. A plain else takes no condition. Writing else (passed == false) doesn't test anything: the parenthesised expression is just evaluated as the whole else branch. To test another condition, write else if (...).
    • Using two ifs when you mean one. Two if statements with opposite conditions work, but they test twice, and if you change one condition and forget the other, both blocks can run, or neither.
    • Assuming a missing branch does nothing wrong. Without an else, the program stays silent in the false case. That is fine when silence is what you want, and a bug when it isn't.
    • Typing errors in the message. "Failed the test" and "Failed the Test" are different strings.

    When both branches only assign a value, a shorter form exists: the conditional expression. With a number temp, const label: string = temp > 30 ? "hot" : "mild"; picks one of two values. Use the if-else form while you are learning, and whenever a branch holds more than one statement.

    Key takeaways

    • else runs when the if condition is false, and has no condition of its own.
    • Exactly one of the two blocks runs each time.
    • Write } else { directly after the closing brace of the if block.
    • An else can't exist without a matching if.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free