Learn JavaScript
❯ browser_dom.storage

localStorage & sessionStorage in JavaScript

$concept

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.

$how it works
1

local persists, session doesn't

localStorage spans sessions; sessionStorage spans the tab lifetime β€” choose by desired survival.

2

Strings only

setItem(k, JSON.stringify(obj)) in, JSON.parse(getItem(k)) out β€” objects need the round trip.

3

Guard everything

try/catch around access (private-mode throws, quotas throw) plus null checks on reads.

4

Sync tabs with events

window storage events notify other tabs of changes β€” multi-tab state stays coherent.

$example
try {
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme"));
} catch (e) {
console.log("storage unavailable");
}
Output
dark
1The theme string persists under its key, surviving reloads.
2Reading it back prints dark β€” round trip through disk-backed storage.
3The try/catch keeps private-mode and quota failures graceful.
$use cases
Theme, preference, and draft persistence across sessions
Tab-scoped wizard state in sessionStorage
JSON round-trips for structured client data
IndexedDB graduation when size or structure outgrows strings

Recommended resourcesAffiliate links Β· may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice β€” pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from β€” great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself β€” building beats watching.