Start learning free

LESSON 75 OF 414 · CONDITIONAL STATEMENTS

If-else Statements in TypeScript

Lesson

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 referred 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