Frontend Master

JavaScript Curriculum

Web Storage
+50 XP

Web Storage

easy
~25 min·50 XP

The coffee shop cart keeps emptying on page refresh. User preferences reset every visit. Web Storage fixes this — persist the cart, theme preference, and last-viewed category without a server.

Web Storage

The browser gives you two storage buckets you can read and write with JavaScript. No server, no cookies, no expiry headers — just a simple key/value store that survives page reloads.

localStorage — Interactive Explorer

Set, get, remove, and clear items in the simulated localStorage:

browser storage — interactive simulator

localStorage contents

localStorage

  • Persists forever — survives page closes, browser restarts
  • Scoped to origin (domain + protocol + port)
  • Synchronous — blocks the main thread if reading large data
  • ~5MB limit. Strings only — JSON.stringify for objects
</storageexplorer2>
⚠️localStorage only stores strings
Every value is stored as a string. `localStorage.setItem('count', 42)` stores `"42"`, not `42`. When you read it back, `getItem('count')` returns `"42"` — a string. For objects and arrays, you must use `JSON.stringify` to save and `JSON.parse` to restore.

localStorage vs sessionStorage

Same API, very different lifetime — knowing when to use which matters:

<storagevsession></storagevsession>

💡When to use each
Use `localStorage` for anything the user expects to persist — theme, cart, auth token, preferences. Use `sessionStorage` for temporary state that should reset when the tab closes — wizard step, unsaved form draft, search state. Never store sensitive data (passwords, full credit card numbers) in either.

Storing Objects and Arrays with JSON

localStorage only holds strings — JSON bridges the gap:

json-storage.js2 items
Espresso£2.50
2
Croissant£2.00
1
ℹ️Always wrap getItem in try/catch
If stored JSON is corrupted (manually edited, truncated, or from an old app version), `JSON.parse` throws. Always wrap reads in try/catch and provide a fallback: `const cart = getStored('cart', [])`. This prevents one bad storage entry from breaking your entire app.

Your Challenge

Build saveCart(items) — calls localStorage.setItem('cart', JSON.stringify(items)). Build loadCart() — reads and parses, returns [] if missing or invalid. On page load call loadCart() and render the items. Wire the order button to add to cart and call saveCart.

Challenge

Build a cart that persists across page refreshes. On page load, read the cart from localStorage with JSON.parse. On every cart change, write it back with JSON.stringify. Add a clear button that calls localStorage.removeItem('cart').

localStoragesessionStoragesetItemgetItemremoveItemJSON.stringifyJSON.parsestorage-events5MB-limitsame-origin
Web Storage | Nexus Learn