JavaScript Fundamentals

Storage, Classes and a Complete Mini App

45 min

Browser storage

localStorage.setItem("theme", "dark");
localStorage.getItem("theme");          // "dark" (strings only)
localStorage.setItem("cart", JSON.stringify(cart));
const saved = JSON.parse(localStorage.getItem("cart") || "[]");
localStorage.removeItem("cart");
  • Data stays per site, per browser. It is not shared across devices.
  • Never store secrets or session tokens in localStorage: any script on the page (including an XSS payload) can read it. Use HttpOnly cookies for sessions.
  • Wrap reads in try/catch: private browsing modes can throw.

Classes

class Cart {
  #items = [];                       // private field

  add(product, qty = 1) {
    const line = this.#items.find(i => i.id === product.id);
    line ? (line.qty += qty) : this.#items.push({ ...product, qty });
  }

  get totalCents() {
    return this.#items.reduce((sum, i) => sum + i.cents * i.qty, 0);
  }

  toJSON() { return this.#items; }
}

Organising code

app/
├── index.html
├── main.js        // wires everything together
├── cart.js        // export class Cart
├── api.js         // export async function getProducts()
└── ui.js          // export function renderCart(cart)

Keep data logic (cart), network calls (api) and DOM code (ui) separate. Each becomes easy to test and change.

Capstone: a mini storefront

Build a single-page shop:

  1. Load products from a local products.json with fetch.
  2. Render product cards with createElement (no innerHTML for data).
  3. Add-to-cart buttons using event delegation.
  4. A cart panel showing items, quantities and total; quantities can change.
  5. Persist the cart in localStorage and restore it on reload.
  6. A checkout form with validation that "submits" by logging the order.
  7. Works with the keyboard; buttons are real <button> elements.

Next steps

  • HTML/CSS Mastery to make it look professional.
  • React + Next.js for larger interfaces.
  • API Design & REST to build the server side your frontend talks to.

Check yourself

  • Why are session tokens unsafe in localStorage?
  • What does a #private field prevent?
  • Why separate API, data and UI code into modules?

Your progress is saved in this browser only.

Submit for review (10 points)