JavaScriptEasy
Difference: LocalStorage vs SessionStorage?
Both store string key-value pairs in the browser with the same API, but localStorage persists until it is cleared (across tabs and restarts), while sessionStorage lasts only for one tab's session and is deleted when that tab closes.
localStorage | sessionStorage | |
|---|---|---|
| Lifetime | Until cleared by code, the user or the browser | Until the tab/window closes |
| Shared between tabs (same origin) | Yes | No, each tab has its own |
| Survives reload | Yes | Yes |
| Capacity | About 5 MB per origin | About 5 MB per origin |
storage event in other tabs | Yes | No |
API (identical)
setItem(key, value), getItem(key) (returns null if missing), removeItem(key), clear(), key(index), length.
Important details
- Strings only: store objects with
JSON.stringifyand read them with a guardedJSON.parse. - Synchronous: it blocks the main thread; fine for small data, bad for large or frequent writes.
- Can throw: in private browsing modes, when storage is disabled, or when the quota is full. Wrap access in
try/catch. - Not secure: any JavaScript on the page (including an XSS payload) can read it. Never store auth tokens or secrets there; prefer HttpOnly cookies for sessions.
- Not available on the server (SSR), so read it inside effects or event handlers.
Choosing
localStorage: preferences, drafts, cached non-sensitive data.sessionStorage: per-tab state like a multi-step form or a scroll position.- Larger or structured data: IndexedDB.
Code example
js
1// A small, safe wrapper: JSON + error handling (storage can be blocked or full)2const store = (storage) => ({3 get(key, fallback = null) {4 try {5 const raw = storage.getItem(key);6 return raw === null ? fallback : JSON.parse(raw);7 } catch {8 return fallback;9 }10 },11 set(key, value) {12 try {13 storage.setItem(key, JSON.stringify(value));14 return true;15 } catch (e) {16 console.warn("Could not save:", e.name); // e.g. QuotaExceededError17 return false;18 }19 },20});2122// Even *reading* window.localStorage can throw (privacy settings, sandboxed iframes), so test it safely23function getStorage(kind) {24 try {25 const s = window[kind];26 s.setItem("__test__", "1");27 s.removeItem("__test__");28 return s;29 } catch {30 console.warn(`${kind} is unavailable here - using memory instead`);31 const mem = new Map(); // same API, lost on reload32 return { getItem: (k) => mem.get(k) ?? null, setItem: (k, v) => mem.set(k, String(v)), removeItem: (k) => mem.delete(k) };33 }34}3536const localStore = getStorage("localStorage");37const sessionStore = getStorage("sessionStorage");38const local = store(localStore); // survives restarts, shared across tabs39const session = store(sessionStore); // this tab only4041local.set("preferences", { theme: "dark", fontSize: 16 });42session.set("checkoutStep", 2);4344console.log(local.get("preferences").theme, session.get("checkoutStep")); // dark 245console.log(typeof localStore.getItem("preferences")); // "string" - stored as JSON text46console.log(local.get("missing", "default")); // default4748// Other tabs are notified when localStorage changes (not sessionStorage)49window.addEventListener("storage", (e) => console.log(`${e.key} changed in another tab`));5051localStore.removeItem("preferences");52sessionStore.removeItem("checkoutStep");
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.