Skip to the content

Project: shopping cart

JavaScript · Unit 14: Modern classes

You're going to build a shopping cart. It keeps its lines in a private field, so nobody can poke at them from outside, and answers with computed properties: how many units it carries and how much there is to pay.

Here's the base, with add and units already written:

class Cart {
  #items = [];
  add(price, qty) {
    const line = {
      price: price,
      qty: qty,
    };
    this.#items.push(line);
  }
  get units() {
    let n = 0;
    for (const i of this.#items) {
      n += i.qty;
    }
    return n;
  }
}
const c = new Cart();
c.add(12, 3);
console.log(c.units);

Prints

3

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Complete the code

    Fill in the class so the lines stay private and units is used without parentheses.

  2. 2. Write the code

    Write get total(): what the whole cart costs, that is the price times the quantity of every line, added up. An empty cart costs 0. The buy function below is already written and is what tests it.

  3. 3. Write the code

    The saved cart comes back as text. Write static load(text): build a new Cart and add one line for every object in the JSON, with its price and its qty. Return that cart. The trip function below saves one and loads it again.

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →