JavaScript Notes
Master the JavaScript Web Storage API — localStorage and sessionStorage. Learn setItem, getItem, removeItem, clear, JSON storage, storage events, and comparisons with cookies and IndexedDB.
The Web Storage API provides two simple key-value storage mechanisms built into every browser: localStorage and sessionStorage. They let you store string data on the client side without the complexity of cookies or databases — perfect for user preferences, shopping carts, form drafts, and session data.
💡 Key insight: Both storage types are synchronous, same-origin, and store only strings. To store objects, serialize withJSON.stringifyand deserialize withJSON.parse.
localStorage vs sessionStorage
| Feature | localStorage | sessionStorage |
|---|---|---|
| Persistence | Until explicitly cleared | Until the tab is closed |
| Shared across tabs | ✅ Yes | ❌ No (each tab is isolated) |
| Shared across windows | ✅ Yes (same origin) | ❌ No |
| Survives page refresh | ✅ Yes | ✅ Yes |
| Survives browser restart | ✅ Yes | ❌ No |
| Storage limit | ~5–10 MB | ~5 MB |
Core Methods
Both localStorage and sessionStorage share the same API:
// Set an item
localStorage.setItem("username", "alice");
sessionStorage.setItem("activeTab", "dashboard");
// Get an item
const user = localStorage.getItem("username");
const tab = sessionStorage.getItem("activeTab");
console.log(user, tab);
// Remove a specific item
localStorage.removeItem("username");
// Clear all items for this origin
localStorage.clear();
// Get number of stored items
console.log(localStorage.length);
// Get key by index
console.log(localStorage.key(0));"alice" "dashboard"
// After removeItem("username"): key is gone
// After clear(): all keys removed
0
null // (after clear, no keys remain)Storing Objects with JSON
Web Storage only stores strings. Use JSON.stringify / JSON.parse:
const user = {
name: "Alice",
age: 28,
preferences: { theme: "dark", language: "en" }
};
// Store object
localStorage.setItem("user", JSON.stringify(user));
// Read object back
const stored = JSON.parse(localStorage.getItem("user"));
console.log(stored.name);
console.log(stored.preferences.theme);"Alice" "dark"
Safe helper functions:
[{ id: 1, qty: 2 }, { id: 5, qty: 1 }]
[]Iterating All Storage Items
"theme: dark" "lang: en" "fontSize: 16"
Or use Object.entries after spreading (modern approach):
const allItems = { ...localStorage };
console.log(allItems);{ theme: "dark", lang: "en", fontSize: "16" }Listening for Storage Changes Across Tabs
The storage event fires in other open tabs when localStorage changes.
// (When Tab A calls localStorage.setItem("theme", "light"))
"Key changed: theme"
"Old value: dark"
"New value: light"
"Origin: https://example.com/settings"⚠️ The storage event does not fire in the tab that made the change — only in other tabs/windows of the same origin.Practical: Dark Mode Preference
"Theme set to: light" // first visit (no saved preference) "Theme set to: dark" // after toggle // On next page load: "Theme set to: dark" (persisted)
Web Storage vs Cookies vs IndexedDB
| localStorage | sessionStorage | Cookies | IndexedDB | |
|---|---|---|---|---|
| Capacity | ~5–10 MB | ~5 MB | ~4 KB | Hundreds of MB |
| Persistence | Until cleared | Tab close | Expiry date | Until cleared |
| Sent to server | ❌ No | ❌ No | ✅ Every request | ❌ No |
| Async API | ❌ Synchronous | ❌ Synchronous | ❌ Sync | ✅ Async |
| Searchable | ❌ No | ❌ No | ❌ No | ✅ Yes |
| Use case | Prefs, cart, tokens | Session temp data | Auth sessions | Large/structured data |
When to Use Web Storage
- User preferences — theme, language, font size
- Shopping cart — persist items between page navigations
- Form drafts — auto-save form data so users don't lose work on refresh
- Auth tokens — store JWT tokens (but consider
httpOnlycookies for sensitive tokens) - Feature flags — remember if user has seen onboarding
Common Mistakes
- Storing sensitive data in localStorage — it's accessible via JavaScript and vulnerable to XSS. Never store passwords or highly sensitive tokens in localStorage.
- Forgetting to parse JSON —
getItemalways returns a string. Wrap inJSON.parsefor objects/arrays. - Not handling
nullfromgetItem— if the key doesn't exist,getItemreturnsnull. Always provide defaults. - Exceeding the storage quota — ~5MB limit. Wrap
setItemin try/catch to handleQuotaExceededError. - Assuming data is shared across tabs with
sessionStorage— each tab has its own isolatedsessionStorage. - Using localStorage for large data — for structured queries or large datasets, use IndexedDB.
Interview Questions
Q1. What is the difference between localStorage and sessionStorage?
localStoragepersists until explicitly cleared — it survives tab close, browser restart, and is shared across all tabs of the same origin.sessionStorageis scoped to a single browser tab and is cleared when the tab is closed.
Q2. What data types can Web Storage store?
Only strings. To store objects or arrays, useJSON.stringify()when writing andJSON.parse()when reading.
Q3. What is the storage limit for localStorage?
Most browsers allow ~5–10 MB per origin. Exceeding it throws aQuotaExceededError(aDOMException). Always wrapsetItemin try/catch for production code.
Q4. Does localStorage data get sent to the server with requests?
No. Unlike cookies, Web Storage data is never automatically included in HTTP requests. It lives only in the browser and must be read by JavaScript and manually sent if needed.
Q5. When does the storage event fire?
Thestorageevent fires onwindowin other tabs/windows of the same origin whenlocalStorageis modified. It does not fire in the tab that triggered the change.
Q6. Is localStorage secure for storing authentication tokens?
localStorageis accessible via JavaScript, making it vulnerable to XSS attacks. For highly sensitive auth tokens, preferhttpOnlycookies (not accessible via JS). For less sensitive tokens, localStorage is acceptable with a strong Content Security Policy (CSP).
Q7. How do you handle a full localStorage gracefully?
``js try { localStorage.setItem(key, value); } catch (e) { if (e.name === "QuotaExceededError") { console.warn("Storage full — clearing old data"); localStorage.removeItem(oldKey); localStorage.setItem(key, value); } } ``Q8. Can a Service Worker access localStorage?
No. Service Workers run outside the main thread and have no access tolocalStorageorsessionStorage. Use the Cache API or IndexedDB for Service Worker storage.
Key Takeaways
localStorageis permanent (until cleared);sessionStorageis tab-scoped (cleared on tab close).- Both APIs are synchronous and store only strings — use
JSON.stringify/parsefor objects. localStorageis not shared between tabs insessionStorage, but is shared across all tabs withlocalStorage.- The
storageevent lets other tabs react to localStorage changes in real time. - Never store passwords or highly sensitive data in Web Storage — it's readable via JavaScript.
- For large, structured, or indexed data, use IndexedDB instead.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Web Storage API in JavaScript — localStorage & sessionStorage Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, browser, apis, web
Related JavaScript Master Course Topics