Start learning free

LESSON 160 OF 410 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V3 - Free Shipping in JavaScript

Practice

Use an if/else to decide whether to charge shipping based on a free-shipping threshold.

You start with:

const subtotal = 75;
const shipping_cost = 10;
const free_shipping_threshold = 100;

Build:

Subtotal: $75
Shipping: $10
Total: $85

Rules:

  • If subtotal >= free_shipping_threshold, set shipping to 0; otherwise set it to shipping_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 be Subtotal: $120, Shipping: $0, Total: $120.
  • Join the three lines with a newline "\n" into one string result, then print it with console.log(result).

Decide shipping in an if/else first, then build the three lines.

Declare let shipping; before the if, so it is still visible after the if/else, then assign it in both branches.

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

const subtotal = 75;
const shipping_cost = 10;
const free_shipping_threshold = 100;

let shipping;
if (subtotal >= free_shipping_threshold) {
    shipping = 0;
} else {
    shipping = shipping_cost;
}
const total = subtotal + shipping;
const line1 = "Subtotal: $" + subtotal;
const line2 = "Shipping: $" + shipping;
const line3 = "Total: $" + total;
const result = line1 + "\n" + line2 + "\n" + line3;
console.log(result);

STEP 1 OF 11
    Ctrl + Enter to check

    Shopping Cart V3 in JavaScript

    Keep going with JavaScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free