Skip to content
Lesson 6 of 15

Step 1 of 5 · Reading · ~4 min

Learn

Control Flow

Conditionals

A conditional lets a program choose between paths. By the end of this lesson you can order a chain of if branches correctly, combine conditions with &&, || and ! without precedence surprises, and use switch when one value has several known cases. TypeScript adds one extra gift: the compiler follows your conditions and refines types as it goes.

if / else if / else

const weight: number = 42;

if (weight > 100) {
    console.log("freight");
} else if (weight > 10) {
    console.log("parcel");
} else {
    console.log("letter");
}

Conditions are checked from the top. The FIRST one that is true wins and everything after it is skipped. That makes order matter: if the conditions overlap, put the most specific one first. Writing weight > 10 before weight > 100 would label every freight load a parcel, because 150 is also greater than 10.

Always ===, never ==

"5" == 5;   // true:  loose equality converts the operands first
"5" === 5;  // false: strict equality compares type AND value

== coerces types silently and produces famous absurdities. Use === and !== only.

Combining conditions

&& means and, || means or, ! means not. They are short-circuit operators: in a && b, if a is false then b is never evaluated, which is what makes this safe:

if (count !== 0 && total / count > 10) { /* never divides by zero */ }

When you mix them, && binds tighter than ||, the same way * binds tighter than +. Take a ticket rule: children under 5 and seniors from 65 ride free, but only on weekdays.

const free1: boolean = weekday && age < 5 || age >= 65;     // parsed as (weekday && age < 5) || age >= 65
const free2: boolean = weekday && (age < 5 || age >= 65);   // what the rule says

The first form lets every senior ride free on weekends, because the || splits the expression in two. When a rule mixes the operators, add parentheses to say what you mean, even where they are not strictly required.

switch

When one value is compared against several constants, switch is tidier than a long chain:

const day: number = 6;

switch (day) {
    case 6:
    case 7:
        console.log("weekend");        // 6 and 7 share this branch
        break;
    case 1:
        console.log("start of week");
        break;
    default:
        console.log("weekday");
}

Cases fall through to the next one until a break. Stacking two case labels with no code between them is the deliberate form of that. Forgetting the break after a branch with code is the accidental form: execution runs on into the next case. (Inside a function, a return also ends the switch; the function-types lesson covers functions.)

Type narrowing

const value = JSON.parse('"hello"') as string | number;   // either a string or a number

if (typeof value === "string") {
    console.log(`text of length ${value.length}`);    // value is string here
} else {
    console.log(`number: ${value.toFixed(2)}`);       // only number is left here (toFixed(2) keeps 2 decimals)
}

Inside the if, the compiler knows value is a string, so .length is allowed; in the else, only number remains. Your runtime checks and the compile-time types work together, with no cast.

The ternary expression

const kind = weight % 2 === 0 ? "even" : "odd";

cond ? a : b is an expression, so it can be assigned or returned. Different branch types give a union: cond ? "yes" : 0 has type string | number.

Common mistakes

  • Wrong branch order. A broad condition placed first hides every narrower branch below it.
  • Unparenthesized && with ||. a && b || c is (a && b) || c.
  • = instead of ===. if (x = 5) assigns and is always truthy.
  • Missing break or return in a switch. The next case runs too.

Your exercise

Work out how many days a given month of a given year has, including leap-year Februaries. The starter reads and converts the year and month. The leap-year rule combines three divisibility tests, so parentheses and branch order both matter.

Up nextLoops and IterationControl Flow

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…