Skip to content

Shopping Cart Logic

Medium ~35 min

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. 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.

    Code
    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;
    }

    Expected result

    Adding the same product twice increases its quantity instead of creating a duplicate.

  2. 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.

    Code
    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;
    }

    Expected result

    removeItem('apple', 2) reduces apple's quantity by 2; removeItem('apple') removes it entirely.

  3. 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.

    Code
    function 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. 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.

    Code
    function 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. 5

    Test the full flow

    Add several products, remove one, and run checkout with a discount and tax to see the complete breakdown.

    Code
    addItem({ 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

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

  • Arrays

    Array methods find, filter, and reduce drive the cart logic.

  • Objects

    Each cart item is an object with id, name, price, and quantity.

Related Practice

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to topic