Project: shopping cart
JavaScript · Unit 14: Modern classes
- Full plan
- JavaScript
- Project
- 3 exercises
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. Complete the code
Fill in the class so the lines stay private and
unitsis used without parentheses.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. Thebuyfunction below is already written and is what tests it.3. Write the code
The saved cart comes back as text. Write
static load(text): build a newCartand add one line for every object in the JSON, with itspriceand itsqty. Return that cart. Thetripfunction below saves one and loads it again.
It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.