localStorage & sessionStorage in JavaScript
Web Storage persists string key-values: localStorage survives restarts (per origin, ~5MB), sessionStorage dies with the tab. Both are synchronous (blocking β keep values small), string-only (JSON.stringify/parse for objects), and shareable across same-origin tabs via storage events.
Never store secrets (XSS-readable, unlike httpOnly cookies), wrap access in try/catch (private mode and quotas throw), and namespace keys per app version. For structured or large client data, IndexedDB replaces both.
local persists, session doesn't
localStorage spans sessions; sessionStorage spans the tab lifetime β choose by desired survival.
Strings only
setItem(k, JSON.stringify(obj)) in, JSON.parse(getItem(k)) out β objects need the round trip.
Guard everything
try/catch around access (private-mode throws, quotas throw) plus null checks on reads.
Sync tabs with events
window storage events notify other tabs of changes β multi-tab state stays coherent.
try { localStorage.setItem("theme", "dark"); console.log(localStorage.getItem("theme"));} catch (e) { console.log("storage unavailable");}Recommended resourcesAffiliate links Β· may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself β building beats watching.