Shopping Cart in JavaScript
Track a cart in JavaScript with a Map keyed by product ID and integer paise prices. Combine quantities and reduce totals; this console demo has no checkout.
Run this example once in a fresh browser console. The console shows the printed results.
1const cart = new Map();2function add(product, quantity = 1) {3 if (!Number.isInteger(quantity) || quantity < 1) throw new Error('Quantity must be a positive integer');4 if (!Number.isInteger(product.pricePaise) || product.pricePaise < 0) throw new Error('Price must be non-negative integer paise');5 const old = cart.get(product.id);6 cart.set(product.id, { ...product, quantity: (old?.quantity || 0) + quantity });7}8function remove(id) { cart.delete(id); }9function totalPaise() { return [...cart.values()].reduce((sum, item) => sum + item.pricePaise * item.quantity, 0); }10add({ id: 'notebook', name: 'Notebook', pricePaise: 4500 }, 2);11add({ id: 'pen', name: 'Pen', pricePaise: 1000 });12console.log('Total: ₹' + (totalPaise() / 100).toFixed(2));13remove('pen');14console.log('After removing pen: ₹' + (totalPaise() / 100).toFixed(2));
Sample Output
Total: ₹100.00
Two notebooks cost 90 rupees and the pen adds 10.
After removing pen: ₹90.00
Deleting the pen leaves only the two-notebook line total.
In this one
- Group products by ID with a Map
- Track positive item quantities
- Calculate totals in integer paise
- Separate cart display from payment security
How it works
- 1
Create a Map keyed by product ID.
- 2
Validate quantity and unit price before adding.
- 3
Merge a repeated ID by increasing its quantity.
- 4
Multiply unit paise by quantity and sum the rows.
- 5
Print ₹100.00, remove the pen, and print ₹90.00.
Edge cases
Zero or negative quantity
An invalid count can make the total misleading.
Reject non-integer and non-positive additions. Use a separate update or remove action if you want quantity zero to remove an item.
Browser price edited
Anyone can change local JavaScript values.
Treat browser totals as a preview. Real checkout must look up trusted prices on the server.
What's going on
This shopping cart stores products, combines quantities, removes a product, and calculates a total. A stationery order makes the numbers easy to check: two notebooks at 45 rupees each and one pen at 10 rupees cost 100 rupees.
A Map keeps one entry for each product ID. Adding the same product again increases its quantity instead of creating an unrelated duplicate row. Prices are stored as integer paise, where 100 paise make one rupee. This avoids many decimal-fraction surprises during addition and multiplication for small amounts.
The total multiplies each unit price by its quantity and adds the line totals. Dividing by 100 and using toFixed(2) formats the display in rupees. Removing the pen leaves 90 rupees. This browser-console lesson is only cart logic, not a checkout. A real store must verify prices, stock, and payment on its server rather than trusting values a browser can change.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the total for two 4500-paise notebooks?
Pick an answer to check it.
Question 2
Who must verify checkout prices?
Pick an answer to check it.
Questions people ask
Why store 4500 instead of 45?
4500 is the price in paise. Integer small-unit amounts avoid common decimal rounding problems in simple totals.
What if I add a notebook twice?
Its ID matches, so the existing quantity increases instead of adding a second Map entry.
Does remove take a product name?
No. It takes the stable product ID, such as pen.