localStorage is a synchronous string map per origin that survives tabs and restarts. sessionStorage lasts for the tab. You must JSON.stringify objects, wrap JSON.parse in try/catch, and treat storage as untrusted (users and extensions can edit it). It is not a database and not a secure vault.
This JavaScript cheat sheet is written for people searching for a fast, accurate reference: students, junior developers, and teams shipping production software. Pin it, copy the snippets, and come back when syntax slips.
Quick reference
- Set / get:
localStorage.setItem("k", value)/getItemreturnsstring | null. - JSON: Stringify objects. Parse with try/catch. Remember
nullfrom missing keys. - Remove:
removeItemorclear()(nuclear). - session: Same API, tab-scoped. Good for wizard drafts you do not want on the next visit.
- Quota: Often ~5MB per origin.
setItemthrowsQuotaExceededError. - Sync: Blocks the main thread. Do not store megabytes or write on every keystroke without debounce.
- Privacy: Not HTTP-only. Any XSS can read it. Never store session tokens if you can use HttpOnly cookies.
- Events:
storageevent fires in other tabs, not the one that wrote.
Copy-paste examples
JSON helper with optional expiry
Store a wrapper { exp, value }. Missing or stale keys return the fallback.
function setJSON(key, value, ttlMs) {
const rec = { exp: ttlMs ? Date.now() + ttlMs : null, value };
localStorage.setItem(key, JSON.stringify(rec));
}
function getJSON(key, fallback = null) {
const raw = localStorage.getItem(key);
if (!raw) return fallback;
try {
const rec = JSON.parse(raw);
if (rec.exp && Date.now() > rec.exp) {
localStorage.removeItem(key);
return fallback;
}
return rec.value;
} catch {
return fallback;
}
}Common mistakes
- Storing objects without stringify (
setItemcallstoString→[object Object]). - Keeping JWTs or passwords in localStorage on a site with any XSS surface.
- Writing on every
inputevent in a large form without debounce. - Assuming
getItemreturns an object — it is always a string or null.
FAQ
- localStorage vs cookies? Cookies go to the server (unless
document.cookieonly). localStorage does not. Use HttpOnly cookies for auth.
- localStorage vs IndexedDB? IndexedDB is async and larger, for files and many records. localStorage is a small key/value convenience.
- Does Safari private mode allow it? It may throw or evict quickly. Always wrap writes in try/catch and continue without persistence.
Related JavaScript cheat sheets
- Javascript Cheat Sheet 2026
- Javascript Array Methods Cheat Sheet
- Javascript String Methods Cheat Sheet
Build with this stack
When a cheat sheet is not enough — you need a production app, a student FYP, or a custom dashboard — ArpaNeuro builds custom web development and also sells ready-made source code. Request a quote and tell us the stack.
Browse software development services or the source code marketplace if you want a working codebase instead of starting from a blank file.