Storage, Classes and a Complete Mini App
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
HttpOnlycookies 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:
- Load products from a local
products.jsonwithfetch. - Render product cards with
createElement(noinnerHTMLfor data). - Add-to-cart buttons using event delegation.
- A cart panel showing items, quantities and total; quantities can change.
- Persist the cart in localStorage and restore it on reload.
- A checkout form with validation that "submits" by logging the order.
- 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
#privatefield prevent? - Why separate API, data and UI code into modules?
ההתקדמות שלכם נשמרת בדפדפן הזה בלבד.
שליחה לבדיקה (10 נקודות)