JavaScript Notes
Master JavaScript localStorage for persistent browser storage. Learn setItem, getItem, removeItem, clear, storing objects with JSON, storage events, and real-world use cases like dark mode and cart persistence.
What is localStorage?
localStorage is a browser built-in that lets you store key-value pairs persistently in the user's browser. The data survives page refreshes and browser restarts — it stays until you explicitly delete it or the user clears browser data.
Storing Objects and Arrays (JSON)
localStorage only stores strings. To store objects or arrays, serialize with JSON.stringify() and deserialize with JSON.parse().
"Rahul Sharma" "dark" "object" 2 "Headphones" 2 "Cart total: ₹4597"
Safe localStorage Access Pattern
localStorage can throw SecurityError (private browsing) or QuotaExceededError (storage full). Always use try-catch in production code:
// Utility functions for safe localStorage access
const storage = {
get(key, defaultValue = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch (error) {
console.warn(`localStorage.get failed for key "${key}":`, error);
return defaultValue;
}
},
set(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
return true;
} catch (error) {
if (error.name === 'QuotaExceededError') {
console.error('localStorage is full! Cannot save:', key);
} else {
console.warn(`localStorage.set failed for key "${key}":`, error);
}
return false;
}
},
remove(key) {
try {
localStorage.removeItem(key);
} catch (error) {
console.warn(`localStorage.remove failed for key "${key}":`, error);
}
}
};
// Usage
storage.set('theme', 'dark');
const theme = storage.get('theme', 'light'); // 'light' as fallback
console.log(theme); // "dark"
const missing = storage.get('nonexistent', 'default-value');
console.log(missing); // "default-value""dark" "default-value"
Real World Use Case: Dark Mode Persistence
Real World Use Case: Shopping Cart
Added: Headphones, Cart: 1 items Added: Mouse, Cart: 2 items Added: Headphones, Cart: 2 items Total: ₹6797 2
The storage Event — Cross-Tab Communication
// The 'storage' event fires in OTHER tabs (not the current one) when localStorage changes
window.addEventListener('storage', function(event) {
console.log('Storage changed in another tab!');
console.log('Key:', event.key); // changed key
console.log('Old value:', event.oldValue);
console.log('New value:', event.newValue);
console.log('URL:', event.url); // tab that made the change
// React to changes from other tabs
if (event.key === 'theme') {
document.body.className = event.newValue;
}
if (event.key === 'logout' && event.newValue === 'true') {
// Another tab logged out — redirect this tab too
window.location.href = '/login';
}
});
// Trigger logout across all tabs
function logoutAllTabs() {
localStorage.setItem('logout', 'true');
localStorage.removeItem('logout'); // Clean up
window.location.href = '/login';
}Common Mistakes
❌ Mistake 1: Storing objects without JSON.stringify
❌ Mistake 2: Not handling null from getItem
❌ Mistake 3: Storing sensitive data in localStorage
// ❌ NEVER store these in localStorage!
localStorage.setItem('password', userPassword); // accessible via XSS!
localStorage.setItem('creditCard', cardNumber); // never do this!
// ✅ Store non-sensitive preferences only
localStorage.setItem('theme', 'dark');
localStorage.setItem('language', 'en');
// JWT tokens in localStorage are acceptable but httpOnly cookies are saferInterview Questions
Q1. What is localStorage and what are its limitations? > localStorage is a browser web storage API for storing key-value string pairs persistently per origin. Limitations: ~5MB storage limit, strings only (objects need JSON), synchronous (can block UI), not accessible server-side, vulnerable to XSS attacks.
Q2. How do you store an object in localStorage? > Serialize with JSON.stringify() before storing, and deserialize with JSON.parse() when reading: localStorage.setItem('key', JSON.stringify(obj)) and JSON.parse(localStorage.getItem('key')).
Q3. What happens if localStorage is full? > setItem() throws a QuotaExceededError (DOMException). Always wrap localStorage writes in try-catch blocks in production code.
Q4. Does the storage event fire in the same tab that made the change? > No! The storage event fires in other tabs/windows of the same origin. It's designed for cross-tab communication. The tab that made the change does not receive the event.
Q5. What is the difference between localStorage and cookies? > localStorage: ~5MB, JS-only, no expiry, not sent with HTTP requests. Cookies: ~4KB, can be httpOnly (no JS access), can have expiry, automatically sent with every HTTP request (good for server-side auth).
Q6. Is localStorage synchronous or asynchronous? > Synchronous — it blocks the main thread. For large data operations, this can cause UI jank. For large storage needs, use IndexedDB which is asynchronous.
Key Takeaways
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for JavaScript localStorage - Complete Guide to Web Storage API.
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, dom, local, storage
Related JavaScript Master Course Topics