Start learning free

LESSON 66 OF 68 · PROJECTS: OBJECT-ORIENTED

Shopping Cart in JavaScript: LineItem and Cart Classes

Practice Read the full explanation

A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.

LineItem

  • constructor(name, price, quantity) stores the three values in this.name, this.price and this.quantity.
  • subtotal() returns this.price * this.quantity, the money this one row adds up to.

Cart

  • It keeps its items in a private field #items that starts as an empty array (the # makes it private to the class).
  • add(item) pushes a LineItem onto #items.
  • total() returns the sum of the subtotals of all items, using reduce: this.#items.reduce((s, it) => s + it.subtotal(), 0). The 0 is where the sum starts, so an empty cart gives 0.

Rules:

  • The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
  • An empty cart has a total of 0.
  • An item with price 5 and quantity 3 has a subtotal of 15.
  • Prices in the driver are whole numbers.

The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:

let cart = new Cart();
cart.add(apple);
cart.add(new LineItem("Bread", 20, 3));
console.log("Total: " + cart.total());
cart.add(new LineItem("Milk", 10, 2));
console.log("Total: " + cart.total());

Expected output:

Empty: 0
Subtotal: 15
Total: 75
Total: 95

Write class LineItem with its constructor and subtotal() first, then class Cart with #items.

reduce keeps a running value s: it starts at 0 and, for every item, becomes s + it.subtotal().

class LineItem {
    constructor(name, price, quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    subtotal() {
        return this.price * this.quantity;
    }
}

class Cart {
    #items = [];

    add(item) {
        this.#items.push(item);
    }

    total() {
        return this.#items.reduce((s, it) => s + it.subtotal(), 0);
    }
}

let empty = new Cart();
console.log("Empty: " + empty.total());
let apple = new LineItem("Apple", 5, 3);
console.log("Subtotal: " + apple.subtotal());
let cart = new Cart();
cart.add(apple);
cart.add(new LineItem("Bread", 20, 3));
console.log("Total: " + cart.total());
cart.add(new LineItem("Milk", 10, 2));
console.log("Total: " + cart.total());

STEP 1 OF 13
    Ctrl + Enter to check

    JAVASCRIPT · PROJECTS: OBJECT-ORIENTED

    Shopping Cart in JavaScript, explained

    Problem overview

    A shop keeps its orders in a cart. The lesson builds two classes that work together:

    • LineItem is one row of the cart: a product name, a price and a quantity. Its constructor takes (name, price, quantity) and stores them in this.name, this.price and this.quantity. Its method subtotal() returns this.price * this.quantity.
    • Cart holds many rows in a private field #items, which starts as an empty array. add(item) appends a LineItem, and total() returns the sum of all the subtotals.

    An empty cart totals 0, and the total is worked out each time it is asked for, from the items the cart holds at that moment. The driver creates an empty cart, checks one subtotal, then fills a cart with an apple (5 each, quantity 3), bread (20, quantity 3) and later milk (10, quantity 2). It prints:

    Empty: 0
    Subtotal: 15
    Total: 75
    Total: 95
    

    The apple row is 15 and the bread row is 60, so the first total is 75. Adding milk contributes 20 more, giving 95.

    Approach: composition and reduce

    The two classes have a "has a" relationship: a cart has line items, it isn't one. This is called composition. Cart doesn't need to know how a row computes its own cost. It only asks each row for its subtotal(), and the row answers. If rows later gain discounts, only LineItem changes.

    For the total, the cart needs one number from a list of rows. The array method reduce does that. It walks the array carrying a running value: it starts at an initial value, and for each element it replaces the running value with whatever the callback returns. Here the start is 0, and each step adds one row's subtotal.

    The alternative is a for loop with a sum variable. It gives the same result, but the lesson uses reduce because summing is exactly what it is for.

    Step by step

    1. Declare LineItem.
    2. Write its constructor with the three parameters name, price and quantity.
    3. Store each value on this. Without this., the values would vanish when the constructor ends. Three assignments make a row remember all three.
    4. Write subtotal(). It returns the price times the quantity of this row. Both numbers live on this.
    5. Declare Cart below LineItem.
    6. Declare the private field #items and start it as an empty array.
    7. Write add(item). It pushes the item onto this.#items, so the rows stay in the order they were added.
    8. Write total(). It returns the reduce over this.#items with a callback that adds it.subtotal() to the running sum s, and 0 as the starting value.

    The solution in JavaScript

    class LineItem {
        constructor(name, price, quantity) {
            this.name = name;
            this.price = price;
            this.quantity = quantity;
        }
    
        subtotal() {
            return this.price * this.quantity;
        }
    }
    
    class Cart {
        #items = [];
    
        add(item) {
            this.#items.push(item);
        }
    
        total() {
            return this.#items.reduce((s, it) => s + it.subtotal(), 0);
        }
    }
    
    let empty = new Cart();
    console.log("Empty: " + empty.total());
    let apple = new LineItem("Apple", 5, 3);
    console.log("Subtotal: " + apple.subtotal());
    let cart = new Cart();
    cart.add(apple);
    cart.add(new LineItem("Bread", 20, 3));
    console.log("Total: " + cart.total());
    cart.add(new LineItem("Milk", 10, 2));
    console.log("Total: " + cart.total());
    

    The details a learner might trip on:

    • The second argument of reduce matters. The 0 is the starting value. Without it, reduce would use the first row as the starting value, and adding a subtotal to a LineItem object builds a string: with the apple and bread rows the result is "[object Object]60", not a number. And on an empty array, reduce with no starting value throws TypeError: Reduce of empty array with no initial value. With the 0, an empty cart simply returns 0.
    • Reading the callback. (s, it) => s + it.subtotal() takes the running sum s and the current element it, and returns the new sum. An arrow function with an expression body returns that expression automatically.
    • Rows are shared, not copied. add stores the very object it receives. In the driver, the same apple is used for the subtotal check and then added to the cart. If a row's quantity changes later, the cart's next total changes with it. For a row of 4 at quantity 2, the total is 8, and after setting the quantity to 5 it becomes 20.
    • Each cart has its own list. The field initialiser #items = []; runs for each new Cart(), so two carts never share rows.
    • Private means private. cart.items from outside is undefined, and cart.#items is a syntax error. The only ways in are add and total.

    Complexity

    Time: add is O(1). total is O(n) for n rows, because it asks every row for its subtotal each time. That is the cost of working the total out on demand instead of keeping a stored total. The benefit is that the answer can never be out of date.

    Space: the cart stores n references, so O(n). total uses only the running sum.

    Edge cases and common mistakes

    • Leaving out the 0 in reduce. The empty cart would throw instead of printing Empty: 0.
    • Forgetting this. in the constructor. price = price; assigns a parameter to itself and leaves the row without a price, so subtotal() returns NaN.
    • Forgetting return in total or subtotal. The method returns undefined, and the output reads Total: undefined.
    • Zero quantity. A row such as new LineItem("Pen", 3, 0) has a subtotal of 0 and leaves the total unchanged.
    • Keeping a running total in a field. If you update it in add and a row changes later, the stored number goes stale. Recomputing in total() avoids that.
    • Decimal prices. Floating-point arithmetic is inexact: a price of 0.1 with quantity 3 gives 0.30000000000000004. The lesson's driver uses whole numbers, which stay exact.
    • Strings as numbers. * converts numeric strings, so new LineItem("X", 5, "3").subtotal() is 15, but + would join strings. Pass real numbers.

    Testing

    • An empty Cart: total() returns 0.
    • new LineItem("Apple", 5, 3).subtotal() returns 15.
    • A cart with the apple and bread rows returns 75; after adding milk it returns 95.
    • A cart holding one row, new LineItem("Pen", 3, 0), returns 0.
    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free