Guard clauses reject invalid input before the main work starts.

guard clause A guard clause checks a requirement early and returns or throws before the rest of the function runs.

Guard Clauses

cents
guards.ts
Replay: real traced execution (multi-file project)
function priceLabel(cents: number): string {
    if (cents < 0) {
        return "invalid";
    }
    if (cents === 0) {
        return "free";
    }
    return `$${(cents / 100).toFixed(2)}`;
}

const cents: number = 250;
const label: string = priceLabel(cents);

console.log(`price=${label}`);
function priceLabel(cents: number): string {
    if (cents < 0) {
        return "invalid";
    }
    if (cents === 0) {
        return "free";
    }
    return `$${(cents / 100).toFixed(2)}`;
}

const cents: number = -1;
const label: string = priceLabel(cents);

console.log(`price=${label}`);
function priceLabel(cents: number): string {
    if (cents < 0) {
        return "invalid";
    }
    if (cents === 0) {
        return "free";
    }
    return `$${(cents / 100).toFixed(2)}`;
}

const cents: number = 0;
const label: string = priceLabel(cents);

console.log(`price=${label}`);
  1. cents ← 250

    8    return `$${(cents / 100).toFixed(2)}`;9}1011const cents→ 250: number = 250;  //@cents=-1, 012const label: string = priceLabel(cents250);
  2. function priceLabel(cents: number): string

    1function priceLabel(cents250: number): string {2    if (cents < 0) {3        return "invalid";4    }5    if (cents === 0) {6        return "free";7    }8    return `$${(cents / 100).toFixed(2)}`;9}
  3. label ← $2.50

    11const cents: number = 250;  //@cents=-1, 012const label→ $2.50: string = priceLabel(cents250);1314console.log(`price=${label$2.50}`);
    outputprice=$2.50
  1. cents ← -1

    8    return `$${(cents / 100).toFixed(2)}`;9}1011const cents→ -1: number = -1;12const label: string = priceLabel(cents-1);
  2. function priceLabel(cents: number): string

    1function priceLabel(cents-1: number): string {2    if (cents < 0) {
  3. if (cents < 0)

    1function priceLabel(cents: number): string {2    if (cents-1 < 0) {3        return "invalid";4    }
  4. label ← invalid

    11const cents: number = -1;12const label→ invalid: string = priceLabel(cents-1);1314console.log(`price=${labelinvalid}`);
    outputprice=invalid
  1. cents ← 0

    8    return `$${(cents / 100).toFixed(2)}`;9}1011const cents→ 0: number = 0;12const label: string = priceLabel(cents0);
  2. function priceLabel(cents: number): string

    1function priceLabel(cents0: number): string {2    if (cents < 0) {
  3. if (cents === 0)

    3    return "invalid";4}5if (cents0 === 0) {6    return "free";7}
  4. label ← free

    11const cents: number = 0;12const label→ free: string = priceLabel(cents0);1314console.log(`price=${labelfree}`);
    outputprice=free