Week 6 Cheatsheet: Track Quantity & Total
What You’re Building
A cart that:
- Increases quantity for repeated items
- Displays the total price
JavaScript Concepts
- Looping over cart with
.forEach() - Multiplying price Ă— quantity
- Formatting with
.toFixed(2) - Updating DOM with
innerHTML
Example Code
function updateCart() {
cartItemsContainer.innerHTML = "";
let total = 0;
cart.forEach((item) => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
const cartItem = document.createElement("li");
cartItem.innerHTML = `
<span>${item.name}</span>
<span>Qty: ${item.quantity}</span>
<span>$${itemTotal.toFixed(2)}</span>
`;
cartItemsContainer.appendChild(cartItem);
});
cartTotalContainer.innerHTML = `<h2>Total: $${total.toFixed(2)}</h2>`;
}Tips to Remember
- Use
let total = 0at the start, then add each item’s total - Always re-render the cart every time it changes
- Keep price formatting consistent with
.toFixed(2)
Last updated on