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
- Compute
discount. Use a ternary: ifcoupons[coupon]is notundefined, use it; otherwise use 0. The ternarycondition ? a : bevaluates toawhen the condition is true and tobotherwise. - Compute
total. It is the subtotal minus the discount. - Build
result. The textTotal: $followed by the number, joined with+. - Print
resultwithconsole.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]givesNaNfor an unknown code. - Testing for truthiness.
coupons[coupon] ? ... : 0also 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
SAVE50gives 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:
| coupon | Output |
|---|---|
| SAVE20 | Total: $80 |
| SAVE10 | Total: $90 |
| NOPE | Total: $100 |
| save20 | Total: $100 |
