localStorage
Persists until cleared.
localStorage and sessionStorage store small string values in the browser.
localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
localStorage.removeItem("theme");
Browser APIs & BOM
localStorage persists across browser sessions. sessionStorage lasts for the current tab session.
Both APIs store strings. Objects need JSON.stringify before storage and JSON.parse after reading.
Storage is synchronous and limited. Do not use it for large data, secrets or high-frequency writes.
Persists until cleared.
Persists for the tab session.
Everything is stored as text.
Reads and writes can block briefly.
Examples
const settings = { theme: "dark" };
localStorage.setItem("settings", JSON.stringify(settings));
localStorage.setItem("apiToken", token);
// Browser storage is readable by JavaScript on the page.
Code patterns
These examples focus on practical browser APIs: URL state, storage, cookies, clipboard, permissions, observers and offline-capable platform tools.
Simple key/value storage.
localStorage.setItem("theme", "dark");
Missing keys return null.
const theme = localStorage.getItem("theme") ?? "system";
Serialize structured data.
localStorage.setItem("settings", JSON.stringify(settings));
Clear one value.
localStorage.removeItem("settings");
Rules that matter
Browser APIs are powerful because they touch privacy, navigation, storage, permissions and performance. Use them deliberately.
Preferences and draft UI state are good fits.
Use JSON for structured data.
Stored data can be missing or corrupted.
JavaScript-accessible storage is not a vault.
Storage is synchronous.
localStorage and sessionStorage have different lifetimes.
Production thinking
Browser storage makes lightweight personalization possible without a server round trip.
Stored preferences can remember accessible choices such as reduced motion or theme.
Production storage code should version data, handle corruption and avoid sensitive values.
Stored UI preferences should not hide or remove important content by default.
Live code lab
The preview runs inside an isolated iframe. The JavaScript is placed inside the HTML editor for now, so every example stays together and remains easy to understand.
Mini assignment
Practice assignment
Try it yourself
Self-check
If you can explain support, permissions, fallback and cleanup, you are ready to use the API responsibly.
Senior audit upgrade