Shopping Cart Logic
What you'll build
A shopping cart system with functions to add/remove items, calculate subtotal, apply percentage discounts, and compute the final total with tax.
Goals
- Manage a collection of item objects in an array
- Use array methods (find, filter, reduce) for calculations
- Implement quantity tracking and item removal
- Apply discounts and tax to compute the final price
Prerequisites
- Arrays and array methods (push, find, filter, reduce)
- Objects with properties (name, price, quantity)
- Functions with parameters and return values
Steps
- 1
Create the cart and addItem function
Start with an empty cart array. The addItem function takes a product object and quantity. If the product is already in the cart, increase its quantity; otherwise, add a new entry.
Codelet cart = []; function addItem(product, quantity = 1) { const existing = cart.find(item => item.id === product.id); if (existing) { existing.quantity += quantity; } else { cart.push({ ...product, quantity }); } return cart; }Expected result
Adding the same product twice increases its quantity instead of creating a duplicate.
- 2
Implement removeItem
Write a function to remove an item by id, or reduce its quantity if a quantity is specified. If quantity reaches 0, remove the item entirely.
Codefunction removeItem(id, quantity = Infinity) { const item = cart.find(i => i.id === id); if (!item) return cart; item.quantity -= quantity; if (item.quantity <= 0) { cart = cart.filter(i => i.id !== id); } return cart; }Expected result
removeItem('apple', 2) reduces apple's quantity by 2; removeItem('apple') removes it entirely.
- 3
Calculate the subtotal
Use the reduce method to sum up price * quantity for every item in the cart. This gives the subtotal before discounts and tax.
Codefunction getSubtotal() { return cart.reduce((sum, item) => sum + item.price * item.quantity, 0); }Expected result
For items with prices 10 and 20 (quantity 2 each), subtotal is 60.
- 4
Apply discount and tax
Write a checkout function that takes a discount percentage and tax rate, then computes the final total: subtotal → discount → tax.
Codefunction checkout(discountPercent = 0, taxPercent = 0) { const subtotal = getSubtotal(); const discount = subtotal * (discountPercent / 100); const afterDiscount = subtotal - discount; const tax = afterDiscount * (taxPercent / 100); const total = afterDiscount + tax; return { subtotal, discount, tax, total }; }Expected result
checkout(10, 8) on a $100 subtotal gives discount $10, tax $7.20, total $97.20.
- 5
Test the full flow
Add several products, remove one, and run checkout with a discount and tax to see the complete breakdown.
CodeaddItem({ id: 'apple', name: 'Apple', price: 1.50 }, 3); addItem({ id: 'bread', name: 'Bread', price: 3.00 }, 2); addItem({ id: 'milk', name: 'Milk', price: 2.50 }, 1); removeItem('apple', 1); // remove 1 apple console.log('Cart:', cart); console.log('Checkout:', checkout(10, 8));Expected result
Cart shows 2 apples, 2 breads, 1 milk; checkout shows subtotal, discount, tax, and total.
Try it yourself
let cart = [];
function addItem(product, quantity = 1) {
// TODO: add or update item
}
function removeItem(id, quantity) {
// TODO: remove or reduce item
}
function getSubtotal() {
// TODO: sum price * quantity
}
function checkout(discountPercent, taxPercent) {
// TODO: compute final total
}let cart = [];
function addItem(product, quantity = 1) {
const existing = cart.find(item => item.id === product.id);
if (existing) { existing.quantity += quantity; }
else { cart.push({ ...product, quantity }); }
return cart;
}
function removeItem(id, quantity = Infinity) {
const item = cart.find(i => i.id === id);
if (!item) return cart;
item.quantity -= quantity;
if (item.quantity <= 0) { cart = cart.filter(i => i.id !== id); }
return cart;
}
function getSubtotal() {
return cart.reduce((sum, item) => sum + item.price * item.quantity, 0);
}
function checkout(discountPercent = 0, taxPercent = 0) {
const subtotal = getSubtotal();
const discount = subtotal * (discountPercent / 100);
const afterDiscount = subtotal - discount;
const tax = afterDiscount * (taxPercent / 100);
return { subtotal, discount, tax, total: afterDiscount + tax };
}
addItem({ id: 'apple', name: 'Apple', price: 1.50 }, 3);
addItem({ id: 'bread', name: 'Bread', price: 3.00 }, 2);
removeItem('apple', 1);
console.log('Checkout:', checkout(10, 8));What you learned
You built a complete cart system using array methods (find, filter, reduce) and object manipulation — the same patterns used in real e-commerce backends, just with a database instead of an in-memory array.
Related Resources
Related Lessons
Related Practice
- Predict Array map Output
Practice predicting array method results.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.