Start learning free

LESSON 193 OF 289 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in TypeScript: Coupon Lookup with an Object

Practice Read the full explanation

Use an object as a fast lookup table for coupon discounts.

You start with:

const subtotal: number = 100;
const coupon: string = "SAVE20";
const coupons: Record<string, number> = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50};

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with console.log(result).

coupons[coupon] is undefined when the key is missing. Use a ternary to default to 0.

In TypeScript "Total: $" + total converts the number to text for you.

const subtotal: number = 100;
const coupon: string = "SAVE20";
const coupons: Record<string, number> = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50};

const discount: number = coupons[coupon] !== undefined ? coupons[coupon] : 0;
const total: number = subtotal - discount;
const result: string = "Total: $" + total;
console.log(result);

STEP 1 OF 4
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in TypeScript, explained

    Problem overview

    A shopper types a coupon code, and the program has to take the matching amount off the subtotal. The starter defines subtotal (100), the typed coupon ("SAVE20") and a lookup table coupons of type Record<string, number> that maps each valid code to its discount: SAVE10 to 10, SAVE20 to 20 and SAVE50 to 50.

    The program computes total = subtotal - discount, stores the text Total: $80 in result and prints it. An unknown code takes nothing off: with a code that isn't in the table, the output is Total: $100.

    Approach: look the code up, default to zero

    One way to find a discount is a chain of comparisons, if (coupon === "SAVE10") ... else if (coupon === "SAVE20") .... It works, but every new coupon means new code. An object keyed by coupon code turns the problem into a lookup: coupons[coupon] goes straight to the value, however many coupons there are, and adding a coupon means adding one entry to the data.

    The one subtlety is the missing key. Reading a property that doesn't exist doesn't raise an error in JavaScript or TypeScript. It gives undefined. So the code has to check for undefined and substitute 0 itself. A ternary expression does that in one line: coupons[coupon] !== undefined ? coupons[coupon] : 0 means "if the code has an entry, use it; otherwise use 0".

    Because the lookup result decides the discount, and the discount decides the total, the three values are computed in that order: discount, then total, then the text.

    Step by step

    1. Compute discount as a const number. Compare coupons[coupon] with undefined in a ternary. The first branch reads the value, the second gives 0.
    2. Compute total: the subtotal minus the discount.
    3. Build result: the fixed text Total: $ followed by total. The + operator converts the number to text.
    4. Print result with console.log.

    The solution in TypeScript

    const subtotal: number = 100;
    const coupon: string = "SAVE20";
    const coupons: Record<string, number> = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50};
    
    const discount: number = coupons[coupon] !== undefined ? coupons[coupon] : 0;
    const total: number = subtotal - discount;
    const result: string = "Total: $" + total;
    console.log(result);

    Things to know about this code:

    • Record<string, number> is the type of an object whose keys are strings and whose values are numbers. It exists only for the compiler. At run time coupons is an ordinary object.
    • The type says number, but a missing key still gives undefined. With the lesson's compiler settings, coupons["BOGUS"] is typed as a number, so the compiler will not warn you. The !== undefined check is what keeps the program correct.
    • Keys are case-sensitive. With the code save20 in lower case the lookup finds nothing and the output is Total: $100.
    • Shorter forms exist. coupons[coupon] ?? 0 gives the same answers here: the ?? operator replaces only undefined and null. Don't use || for this job, because it would also replace a legitimate discount of 0. With a table entry {"FREE0": 0}, || with a default of 99 gives 99, while ?? keeps the 0.

    Edge cases and common mistakes

    • Unknown code. coupons["BOGUS"] is undefined. Without the check, 100 - undefined is NaN and the output would be Total: $NaN.
    • Inherited property names. An object literal inherits properties such as toString and constructor. If a shopper types toString as the code, coupons["toString"] is a function, which is not undefined, so the lesson's check accepts it as a discount and the program prints Total: $NaN. The same applies to the in operator. When codes come from untrusted input, Object.hasOwn(coupons, coupon) tests only the object's own keys, and a Map avoids the problem entirely: m.get("toString") ?? 0 is 0.
    • A discount larger than the subtotal. The lesson doesn't clamp the total. With a subtotal of 30 and the code SAVE50, the output is Total: $-20. Real shops usually stop the total at 0 with Math.max(0, ...).
    • Calling the object like a function. Lookup uses square brackets, coupons[coupon], not parentheses.

    Testing

    Change coupon in the editor above and compare with these results from the reference solution:

    couponoutput
    SAVE20Total: $80
    BOGUSTotal: $100
    save20Total: $100
    toStringTotal: $NaN
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free