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.

localStoragesessionStorage
LifetimeUntil cleared by code, the user or the browserUntil the tab/window closes
Shared between tabs (same origin)YesNo, each tab has its own
Survives reloadYesYes
CapacityAbout 5 MB per originAbout 5 MB per origin
storage event in other tabsYesNo

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.stringify and read them with a guarded JSON.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. QuotaExceededError
17 return false;
18 }
19 },
20});
21
22// Even *reading* window.localStorage can throw (privacy settings, sandboxed iframes), so test it safely
23function 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 reload
32 return { getItem: (k) => mem.get(k) ?? null, setItem: (k, v) => mem.set(k, String(v)), removeItem: (k) => mem.delete(k) };
33 }
34}
35
36const localStore = getStorage("localStorage");
37const sessionStore = getStorage("sessionStorage");
38const local = store(localStore); // survives restarts, shared across tabs
39const session = store(sessionStore); // this tab only
40
41local.set("preferences", { theme: "dark", fontSize: 16 });
42session.set("checkoutStep", 2);
43
44console.log(local.get("preferences").theme, session.get("checkoutStep")); // dark 2
45console.log(typeof localStore.getItem("preferences")); // "string" - stored as JSON text
46console.log(local.get("missing", "default")); // default
47
48// Other tabs are notified when localStorage changes (not sessionStorage)
49window.addEventListener("storage", (e) => console.log(`${e.key} changed in another tab`));
50
51localStore.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.

Open in study app