JavaScript Project for Portfolio: Shopping Cart
A simple shopping cart that lets users add products, view the cart and calculate the total cost. Build it with a Product class and a ShoppingCart class, try the live demo, and learn how to present it in your portfolio.
How the Shopping Cart Works
A shopping cart is a classic JavaScript project for a portfolio because it shows that you can model real-world things with code. Two classes do the work. The Product class represents a product with a name and a price, and the ShoppingCart class lets users add items, view their cart and determine the final price.
You create instances of products with Product, and an instance of a cart with ShoppingCart. Then you add the products with addProduct(), view the cart with viewCart(), and calculate the total with calculateTotal().
What the finished project does
- Adds products and combines repeated items into one line with a quantity.
- Removes products and changes quantities, with validation.
- Calculates the total exactly by storing prices in cents, avoiding floating-point surprises.
- Runs in two places: in the console, and on a responsive web page with a live cart.
calculateTotal() only printed the total, so you could not reuse the number. The new version returns it, and the console logging happens outside the class. Adding the same product twice used to create two separate lines. Prices were also plain decimals, which can drift: in JavaScript, 0.1 + 0.2 equals 0.30000000000000004.Step 1: The Product and ShoppingCart Classes
The Product class stores an id, a name and a price. Internally the price is saved in cents as an integer, so adding many prices stays exact. The ShoppingCart class keeps its items in a Map keyed by product id, which makes finding, updating and removing a line fast.
// Format a number as US dollars
const money = (n) => new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
}).format(n);
// Product class
class Product {
constructor(id, name, price) {
this.id = id;
this.name = name;
this.priceCents = Math.round(price * 100); // store money as whole cents
}
get price() {
return this.priceCents / 100;
}
}
// Shopping cart class
class ShoppingCart {
constructor() {
this.items = new Map(); // product id -> { product, qty }
}
// Add a product to the cart (repeated products increase the quantity)
addProduct(product, qty = 1) {
const line = this.items.get(product.id);
if (line) line.qty += qty;
else this.items.set(product.id, { product, qty });
}
// Remove a product completely
removeProduct(id) {
this.items.delete(id);
}
// Set a quantity (0 or less removes the line)
setQuantity(id, qty) {
if (qty <= 0) this.removeProduct(id);
else if (this.items.has(id)) this.items.get(id).qty = qty;
}
// Number of items in the cart
get count() {
let n = 0;
this.items.forEach((l) => { n += l.qty; });
return n;
}
// View the cart as text
viewCart() {
if (!this.items.size) return 'Your cart is empty.';
const lines = [];
let i = 1;
this.items.forEach((l) => {
lines.push(i++ + '. ' + l.product.name + ' x' + l.qty + ' - ' +
money(l.product.price * l.qty));
});
return 'Shopping Cart:\n' + lines.join('\n');
}
// Calculate the total cost (returns a number)
calculateTotal() {
let cents = 0;
this.items.forEach((l) => { cents += l.product.priceCents * l.qty; });
return cents / 100;
}
}Why store prices in cents?
Decimal fractions like 0.1 cannot be stored exactly in binary, so repeated addition can produce tiny errors. Whole-number cents are always exact. You only divide by 100 when you display a value or return the total.
Step 2: Create Products and a Cart
Now use the classes. Create a few products, create a cart, add the products, view the cart and calculate the total. Add this code below the classes in cart.js, then run the file in Node.js or paste everything into your browser’s console.
// Create instances of products
const product1 = new Product(1, 'Shirt', 20.99);
const product2 = new Product(2, 'Pants', 35.99);
const product3 = new Product(3, 'Shoes', 49.99);
// Create a shopping cart
const cart = new ShoppingCart();
// Add products to the cart
cart.addProduct(product1);
cart.addProduct(product2);
cart.addProduct(product3);
cart.addProduct(product1); // a second shirt increases the quantity
// View the cart
console.log(cart.viewCart());
// Calculate the total cost
console.log('Total cost: ' + money(cart.calculateTotal()));The output lists each product with its quantity and line total, followed by the final cost. Because calculateTotal() now returns a number, you can also use it for discounts, tax or shipping.
Step 3: Show the Cart on a Web Page
To turn the console project into something visitors can click, connect the same classes to the page. This minimal example loads cart.js and renders the cart into a list. It builds elements with textContent, so product names can never inject HTML into the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Shopping Cart</title>
<style>
body { font-family: Arial, sans-serif; max-width: 480px; margin: 20px auto; padding: 0 16px; }
button { padding: 10px 16px; font-size: 1rem; margin: 4px 4px 4px 0; }
li { display: flex; justify-content: space-between; padding: 6px 0; }
</style>
</head>
<body>
<h1>Shopping Cart</h1>
<div id="shop"></div>
<ul id="cart"></ul>
<p>Total: <strong id="total">$0.00</strong></p>
<script src="cart.js"></script>
<script>
const products = [
new Product(1, 'Shirt', 20.99),
new Product(2, 'Pants', 35.99),
new Product(3, 'Shoes', 49.99)
];
const cart = new ShoppingCart();
products.forEach((p) => {
const b = document.createElement('button');
b.textContent = 'Add ' + p.name + ' (' + money(p.price) + ')';
b.addEventListener('click', () => { cart.addProduct(p); render(); });
document.getElementById('shop').appendChild(b);
});
function render() {
const ul = document.getElementById('cart');
ul.textContent = '';
cart.items.forEach((l) => {
const li = document.createElement('li');
li.textContent = l.product.name + ' x' + l.qty + ' ' + money(l.product.price * l.qty);
ul.appendChild(li);
});
document.getElementById('total').textContent = money(cart.calculateTotal());
}
render();
</script>
</body>
</html>Live Demo: Shopping Cart in Action
This demo uses the same Product and ShoppingCart logic as the code above, with quantity controls and a saved cart. The first three products come from the tutorial and the rest are demo extras. It is a demo only: no payment is processed and nothing is sent anywhere.
Products
Your cart 0
How to Present This JavaScript Project in Your Portfolio
A working cart is a good start, but how you present it matters just as much. Hiring managers and clients look for evidence that you can finish a project and explain your decisions. These steps help a small project stand out:
- Publish the code on GitHub with a clear README that explains what the project does and how to run it.
- Host a live demo on GitHub Pages or any static host, and link to it from the README and your portfolio page.
- Explain your design choices: why prices are stored in cents, and why the cart uses a
Map. - Add tests for the totals, for example that three items add up to exactly the expected amount.
- Show growth: list the extra features you added, such as saved carts, discounts or a checkout summary.
Ideas to extend the cart
- Discount codes and free-shipping thresholds.
- Tax and shipping lines in the order summary.
- Product search and categories using a larger product list.
- A backend that stores orders, so the cart becomes a full e-commerce project.
JavaScript Exercises Using the Shopping Cart
The cart is a great source of javascript exercises for beginners because every method practices a core concept: variables hold the data, functions and methods do the work, and loops and maps process the items. If you want javascript exercises and solutions to compare against, build each feature yourself before checking the code above.
Variables and functions
Start with javascript variables exercises, for example storing a tax rate in a variable and applying it to the total. Then try javascript function exercises by writing small helper functions such as applyDiscount(total, percent) or formatLine(item).
Challenges to try next
These javascript practice exercises with solutions are easy to verify, because the live demo shows the expected behavior. Treat them as javascript tasks for practice, or as quick js exercises for a single sitting:
- Add a
clear()method that empties the cart. - Add a discount code that takes 10% off orders over $100.
- Sort the cart lines by price, highest first.
- Show the most expensive item in the cart in the summary.
For more javascript exercises, browse our JavaScript projects.
Frequently Asked Questions
How do you build a shopping cart in JavaScript?
Create a Product class for the items and a ShoppingCart class that stores them. Add methods to add and remove products, change quantities and calculate the total, then connect those methods to buttons on a page.
Why does 0.1 + 0.2 not equal 0.3 in JavaScript?
Numbers are stored in binary, and some decimals cannot be represented exactly. For money, store prices as whole cents and divide by 100 only when displaying them.
Is this cart secure for a real shop?
No. Anything that runs in the browser can be changed by the visitor, so a real shop must calculate prices and process payments on a server. This project is for learning and for your portfolio.
Is this a good project for a portfolio?
Yes, especially if you publish it on GitHub, host a live demo and explain your design decisions. It shows classes, data handling and DOM updates in a familiar, easy-to-understand app.
Is JavaScript hard for beginners?
It has a gentle start because you see results immediately in the browser. Small projects like this one are a motivating way to learn classes, functions and the DOM.
Keep Building with JavaScript
You built a shopping cart with a Product class and a ShoppingCart class, fixed the precision problems of plain decimals, and connected the logic to a responsive page. It is a compact project that demonstrates object-oriented thinking, and with a README and a live demo it makes a solid addition to your portfolio.
