← Fundamentals
Fundamentals

Branches and pattern matching

Which case applies, and what result does it select?

Keep branch selection separate from the outcome the selected branch returns.

Outcome

Select the intended native branch and preserve the difference between a non-match and a matched negative outcome.

Terminology (3)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Alternative
One candidate branch in a construct that selects among cases.
Fallthrough
Execution continuing from an entered switch case into a later case body.
First match
Selecting the earliest applicable case in the specified order, independently of whether its action is positive.

Selecting among alternatives

Branching chooses which work to perform from several alternatives. Conditions can overlap, and a pattern can describe a value’s structure as well as test its contents. The construct’s ordering, coverage and case-ending rules determine how those alternatives become control flow.

A selection may itself produce a negative result. A matching rule that declines an action is still a match; continuing to search can change the policy. Preserve whether an alternative applied separately from the value it selected.

01Ordered alternatives

A chain chooses the first applicable branch

A parcel arrives with a weight, kind and urgency flag. The desk needs one size route and one service before its ordered dispatch rules decide whether to release it. Check how a branch chain resolves overlapping facts before combining those policies in the intake report.

The parcel carries both heavy and urgent flags. One if/else chain chooses its intake label. Trace the written order to predict which body runs; the labels do not define priority on their own.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const heavy = true;
const urgent = true;

if (heavy) console.log("heavy");
else if (urgent) console.log("express");
else console.log("regular");
Which line prints?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc main.ts --noEmit --skipLibCheck --target es2022 --module nodenext --types node && node main.ts

Save one complete example at a time under the shown filename in a fresh folder. Run the shown command. The browser lab supplies its editor, input fixtures and runner.

02Native case behavior

A matched label is not always an exclusive body

The desk also handles numbered parcel kinds, which select handling actions. For kind 1, check whether entering its case limits execution to that body. Follow the selected native construct through the source rather than importing another language’s case-ending rule.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const kind: number = 1;

switch (kind) {
  case 1:
    console.log("scan");
  case 2:
    console.log("pack");
    break;
  default:
    console.log("hold");
}
Which lines print?

03Match and selected action

A matched case may select a negative outcome

A service choice does not settle dispatch permission. The desk’s helper checks a configured rule’s parcel kind; kind 0 is a wildcard. A present decision means the rule applies, with true for dispatch and false for hold. No match is represented separately. Trace the helper result and the caller’s report.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Rule = { kind: number; dispatch: boolean };

function matchRule(rule: Rule, kind: number): boolean | null {
  if (rule.kind === 0 || rule.kind === kind) return rule.dispatch;

  return null;
}

const result = matchRule({ kind: 1, dispatch: false }, 1);

console.log("matched", result !== null, "dispatch", result);
Which pair prints?

04Practice

Repair the parcel router

Continue the same intake report: preserve one size route, implement the kind-and-urgency service policy, then apply the ordered dispatch list. The complete files supply input decoding and the matching helper; later tasks retain the earlier correct calculations.

For the dispatch list, input supplies a rule count followed by kind/action pairs. Kind 0 matches every parcel kind; action 0 means hold and action 1 means dispatch. Keep the first matching action even when it is hold.

Start the lab

Choose an exclusive size result, combine kind and urgency for service, then keep the first applicable dispatch decision.

  1. easy · F-BRANCH-V4-1 Choose one size route
  2. medium · F-BRANCH-V4-2 Select the native service
  3. hard · F-BRANCH-V4-3 Keep the first applicable decision
In the frontend A display policy can give error priority over loading. Optional

The parcel-tracking view can receive both error and loading as true. Its display policy gives the error view priority. Compare React’s early component return with Svelte’s alternatives in one if block; the status names themselves do not choose the view.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
export function Status({ error, loading }: { error: boolean; loading: boolean }) {
  if (error) return <p>Could not load</p>;
  if (loading) return <p>Loading</p>;

  return <p>Ready</p>;
}

The early component result makes the first true branch terminal.

Sources: React: Conditional rendering,Svelte: if blocks.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.