Each exercise starts with working JavaScript and a change request. Decide what you would tidy first, then open the worked edit. Compare the behaviour at the boundary before moving on.
1. Make the ordinary path visible
You’re about to add a new invoice label. What takes precedence when a paid invoice is also past its due date?
function label(invoice) {
if (!invoice.paid) {
if (invoice.overdue) return "Overdue";
return "Open";
}
return "Paid";
}
Reveal the guard clauses
function label(invoice) {
if (invoice.paid) return "Paid";
if (invoice.overdue) return "Overdue";
return "Open";
}
Paid wins, including when both flags are true. Checking overdue first would silently change which label some customers see. Try all four combinations of flags.
2. Name a threshold
The free-delivery limit is about to change. What unit is the limit in, and which side owns the exact boundary?
function deliveryCents(subtotalCents) {
return subtotalCents >= 5000 ? 0 : 450;
}
Reveal the named amounts
const freeDeliveryThresholdCents = 5000;
const standardDeliveryCents = 450;
function deliveryCents(subtotalCents) {
if (subtotalCents >= freeDeliveryThresholdCents) return 0;
return standardDeliveryCents;
}
At 4,999 cents delivery costs 450 cents. At 5,000 it is free. Those two examples pin down the comparison independently of the new names.
3. Expose the changing input
A receipt preview should be able to choose its own currency. Where does that choice enter the calculation today?
function formatPrice(value) {
return new Intl.NumberFormat("en", {
style: "currency",
currency: settings.currency
}).format(value);
}
const receipt = formatPrice(total);
Reveal the explicit parameter
function formatPrice(value, currency) {
return new Intl.NumberFormat("en", {
style: "currency",
currency
}).format(value);
}
const receipt = formatPrice(total, settings.currency);
The existing caller still reads the live setting when it creates the receipt. A preview can pass its own currency. Compare outputs using USD and JPY to exercise different fractional-digit conventions.
4. Keep a meaningful zero
Two display helpers look similar. Both support an override, and in both cases zero is a valid configured value. Which operation can they share?
function width(settings) {
return settings.width ?? 80;
}
function indent(settings) {
return settings.indent == null ? 4 : settings.indent;
}
Reveal the symmetrical expressions
function width(settings) {
return settings.width ?? 80;
}
function indent(settings) {
return settings.indent ?? 4;
}
For numeric settings, both functions now express the same
missing-value rule. Try an absent key, null, and
0. Replacing the expressions with || would
turn a deliberate zero indent into four spaces.