Start learning free

LESSON 189 OF 285 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in JavaScript: 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 = 100;
const coupon = "SAVE20";
const coupons = {"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 JavaScript "Total: $" + total converts the number to text for you.

const subtotal = 100;
const coupon = "SAVE20";
const coupons = {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50};

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

STEP 1 OF 4
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in JavaScript, explained

    Problem overview

    A shopper types a coupon code, and the program has to take the matching discount off the subtotal. The known codes live in an object, coupons, that maps each code to the amount it takes off: {"SAVE10": 10, "SAVE20": 20, "SAVE50": 50}. With a subtotal of 100 and the code SAVE20 the output is:

    Total: $80

    A code that is not in the object takes nothing off. With NOPE the output would be Total: $100. Shoppers can type anything, so the program must handle unknown codes without breaking.

    Approach: look the code up, default to zero

    One option is a long chain of if statements, one per code. Adding a coupon would then mean changing the logic. An object turns the codes into data: coupons[coupon] finds the discount directly, whether the object has three entries or three thousand. Adding a coupon means adding one entry.

    The lookup has one subtlety. Reading a key that isn't in an object doesn't throw an error; it gives undefined. If that value were subtracted from the subtotal, the result would be NaN. So the program checks for undefined and uses 0 instead.

    Step by step

    1. Compute discount. Use a ternary: if coupons[coupon] is not undefined, use it; otherwise use 0. The ternary condition ? a : b evaluates to a when the condition is true and to b otherwise.
    2. Compute total. It is the subtotal minus the discount.
    3. Build result. The text Total: $ followed by the number, joined with +.
    4. Print result with console.log.

    The solution in JavaScript

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

    Details worth knowing

    The comparison uses !==, the strict operator, which never converts types. That is the habit to keep in JavaScript: === and !== compare the value and the type, while == and != convert first and can surprise you.

    The code is looked up as an exact string. "save20" in lowercase is not a key of coupons, so the total stays 100. If your shop should accept any capitalisation, convert the code with toUpperCase() before the lookup.

    Object keys are always strings. {"SAVE10": 10} and {SAVE10: 10} are the same object, and coupons["SAVE10"] is the same as coupons.SAVE10. The bracket form is the one to use when the key is stored in a variable, as coupon is here.

    A trap: inherited keys

    Every plain object inherits a few properties, such as toString and constructor. A lookup of coupons["toString"] therefore finds a function and not undefined, so the ternary above takes it as a valid discount. With coupon = "toString", the program prints:

    Total: $NaN

    The lesson's coupon codes are safe, but code that reads user input should check only the object's own keys. Object.hasOwn(coupons, coupon) does exactly that: it is true for "SAVE20" and false for "toString". A Map avoids the issue altogether, because it holds only the entries you put in it.

    Complexity

    A lookup in an object takes constant time on average, however many coupons it holds. The whole program does a fixed number of operations, so it runs in O(1) time and extra space.

    Edge cases and common mistakes

    • Not handling the missing key. subtotal - coupons[coupon] gives NaN for an unknown code.
    • Testing for truthiness. coupons[coupon] ? ... : 0 also treats a real discount of 0 as missing. Here that gives the same result, but with other data it could be wrong.
    • Case and spaces. "SAVE20 " with a trailing space is a different key from "SAVE20".
    • Discounts larger than the subtotal. A subtotal of 30 with SAVE50 gives a total of -20. The lesson doesn't set a floor, so the program doesn't add one.

    Testing

    Change coupon in the editor above. The expected output for each code with a subtotal of 100:

    couponOutput
    SAVE20Total: $80
    SAVE10Total: $90
    NOPETotal: $100
    save20Total: $100
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free