Start learning free

LESSON 72 OF 348 · CONDITIONAL STATEMENTS

If Statements in TypeScript: Making Decisions with if and else

Lesson Read the full explanation

TL ; DR:

  • if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

    let isRainy = true;
    if(isRainy) {
        console.log("I bring an umbrella");
    }
    



Full lesson:

As humans, we often make decisions based on conditions. For example, we might go through these decision-making processes during a day:

If it's rainy:
  I bring an umbrella

If I'm hungry:
  I have breakfast

I I'm tired:
  I take a nap

We can also tell the computer to make decisions like these in our programs.


If Statements:

if statements allow us to build programs that can make decisions based on some conditions. Here is the syntax:

if(conditions) {
    // instructions
}

The keyword if tells TypeScript to execute the code inside the curly braces (where we have our TypeScript comment) only if the conditions defined in the parentheses are met.


Boolean conditions:

The conditions inside if statements are known as Boolean conditions and they may only be true or false.

If the boolean condition evaluates to true, the program executes the statements inside curly braces. If it evaluates to false, the statements will not execute.

If you check our example, you'll see that all the conditions there (it's rainy, I'm hungry and I'm tired) are Boolean conditions.

Let's turn those decisions into working code using if statements:

let isRainy = true;
if(isRainy) {
    console.log("I bring an umbrella");
}

The code above prints "I bring an umbrella" since the condition in the parentheses evaluates to true

But this code:

let amHungry = false;
if(amHungry) {
    console.log("I have breakfast");
}

prints nothing since amHungry evaluates to false.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    TYPESCRIPT · CONDITIONAL STATEMENTS

    If Statements in TypeScript, explained

    Why programs need decisions

    Programs rarely run the same lines every time. They look at a situation and choose what to do, just as you would: if it is raining, you take an umbrella; if you are hungry, you eat. An if statement is how TypeScript expresses that choice.

    if (condition) {
        // runs only when the condition is true
    }
    

    The keyword if is followed by a condition in parentheses and a block of code in curly braces. The block runs only when the condition is true. When it is false, the program skips the block and continues after it.

    Boolean conditions

    The condition is a Boolean value, which means it is either true or false. A variable can hold one directly, and comparisons such as age >= 18 produce one.

    let isRainy: boolean = true;
    
    if (isRainy) {
        console.log("I bring an umbrella");
    }
    

    This prints I bring an umbrella, because isRainy is true. With the opposite value, nothing is printed at all:

    let amHungry: boolean = false;
    
    if (amHungry) {
        console.log("I have breakfast");
    }
    

    A condition that is already a Boolean doesn't need a comparison. Write if (isRainy), not if (isRainy == true); both work, but the short form is the usual one.

    Several decisions in a row

    A program can hold any number of if statements, and each one is judged on its own. Take the three decisions from a typical day:

    let isRainy: boolean = true;
    let amHungry: boolean = false;
    let amTired: boolean = true;
    
    if (isRainy) {
        console.log("I bring an umbrella");
    }
    if (amHungry) {
        console.log("I have breakfast");
    }
    if (amTired) {
        console.log("I take a nap");
    }
    console.log("Done");
    

    The output is:

    I bring an umbrella
    I take a nap
    Done
    

    The second block is skipped, and the last line runs no matter what, because it sits outside every if. Code after a block simply continues once the decision has been made.

    Conditions are often comparisons. With let age: number = 20;, the condition age >= 18 is true, so a block guarded by it would run.

    The exercise

    The starting code has a Boolean variable:

    let passed: boolean = true;
    

    The program should print one message when passed is true and a different one when it is false. It takes three steps.

    1. Write the if. Type if (passed) {. The condition is just the variable, because it is already a Boolean.
    2. Add the success message. Inside the block, call console.log("Passed the test");. These lines run only when passed is true.
    3. Add an else. Close the block with } else { on one line, print "Failed" inside, and close with }. An else block has no condition of its own. It runs whenever the if condition was false.

    The finished code:

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

    With passed set to true, it prints Passed the test. Change the first line to false and it prints Failed. Exactly one of the two blocks runs each time.

    Gotchas

    • A single equals sign assigns. if (passed = false) sets passed to false and then tests that value, so it doesn't compare anything. Comparisons use == or ===.
    • Not only Booleans work as conditions. JavaScript treats some other values as false: 0, the empty string, null, undefined and NaN. Everything else, including an empty array and the string "false", counts as true. A number-typed variable can therefore be used in if (count), but that quietly treats 0 as "no". Write the comparison you mean, such as count > 0.
    • Skipping the braces. A single statement can follow if without braces, but then only that one statement is conditional, and adding a second line later is a classic source of bugs. Keeping the braces is safer.
    • Misplaced parentheses or braces. The condition needs its parentheses, and every { needs a matching }. The compiler reports an error if one is missing.
    • Printing with the wrong text. The messages are compared as written, so "Passed the test" and "Passed the Test" are different strings.

    Key takeaways

    • An if statement runs its block only when the condition in parentheses is true.
    • The condition is a Boolean value or any expression that produces one.
    • else covers every case the if did not, and has no condition.
    • Use a comparison to say what you mean, rather than relying on values such as 0 counting as false.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free