Use an if/else to decide whether to charge shipping based on a free-shipping threshold.
You start with:
const subtotal: number = 75;
const shipping_cost: number = 10;
const free_shipping_threshold: number = 100;
Build:
Subtotal: $75 Shipping: $10 Total: $85
Rules:
- If
subtotal >= free_shipping_threshold, setshippingto0; otherwise set it toshipping_cost. total = subtotal + shipping.- Always include all three lines (
Subtotal,Shipping,Total). When shipping is free, the line shows$0: for a subtotal of 120 the lines would beSubtotal: $120,Shipping: $0,Total: $120. - Join the three lines with a newline
"\n"into one stringresult, then print it withconsole.log(result).
Decide
shipping in an if/else first, then build the three lines.
Declare
let shipping: number; before the if, so it is still visible after the if/else, then assign it in both branches.
In TypeScript
"Total: $" + total converts the number to text for you.
const subtotal: number = 75;
const shipping_cost: number = 10;
const free_shipping_threshold: number = 100;
let shipping: number;
if (subtotal >= free_shipping_threshold) {
shipping = 0;
} else {
shipping = shipping_cost;
}
const total: number = subtotal + shipping;
const line1: string = "Subtotal: $" + subtotal;
const line2: string = "Shipping: $" + shipping;
const line3: string = "Total: $" + total;
const result: string = line1 + "\n" + line2 + "\n" + line3;
console.log(result);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
