Syntax
localStorage.setItem(key, value)
localStorage.getItem(key)Examples
Basic Storage Operations
Storing, retrieving, and removing simple string values.
localStorage.setItem("username", "alice");
console.log(localStorage.getItem("username")); // "alice"
localStorage.removeItem("username");
console.log(localStorage.getItem("username")); // null
localStorage.setItem("theme", "dark");
localStorage.setItem("fontSize", "16");
localStorage.clear(); // removes everythingStoring Objects with JSON
localStorage only stores strings, so objects need to be serialized.
const userPrefs = { theme: "dark", fontSize: 16, notifications: true };
localStorage.setItem("preferences", JSON.stringify(userPrefs));
const stored = JSON.parse(localStorage.getItem("preferences"));
console.log(stored.theme); // "dark"
console.log(typeof stored); // "object" - properly restored, not just a stringlocalStorage vs sessionStorage
Choosing the right storage based on how long data should persist.
// Persists across browser restarts, until explicitly cleared
localStorage.setItem("rememberedEmail", "user@example.com");
// Cleared automatically when the tab/browser is closed
sessionStorage.setItem("currentStep", "3");
// Both share the identical API - only the lifetime differsBest practices
- Always wrap JSON.parse() calls on stored data in a try/catch, in case the stored value is missing or corrupted
- Use sessionStorage for temporary, per-tab data (like a multi-step form's progress), and localStorage for data that should persist long-term
- Never store sensitive information (passwords, tokens, personal data) in localStorage - it is accessible to any JavaScript running on the page, including malicious scripts
- Remember storage is per-origin (protocol + domain + port) and has a size limit (typically around 5-10MB) - it is not a substitute for a real database
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification