Set, Get, Remove
// Save data
localStorage.setItem('theme', 'dark');
localStorage.setItem('username', 'alice');
// Read data
const theme = localStorage.getItem('theme'); // 'dark'
const missing = localStorage.getItem('nope'); // null
// Remove one item
localStorage.removeItem('username');
// Clear everything
localStorage.clear();
Storing Objects & Arrays
localStorage only stores strings. Use JSON.stringify to save objects and JSON.parse to read them back:
// Save object
const user = { name: 'Alice', role: 'admin', visits: 5 };
localStorage.setItem('user', JSON.stringify(user));
// Read object back
const stored = localStorage.getItem('user');
const user = stored ? JSON.parse(stored) : null;
console.log(user.name); // 'Alice'
// Save array
const cart = [{ id: 1, qty: 2 }, { id: 5, qty: 1 }];
localStorage.setItem('cart', JSON.stringify(cart));
const savedCart = JSON.parse(localStorage.getItem('cart') || '[]');
Helper Functions
// Safe get with default value
function getStorage(key, defaultValue = null) {
try {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
} catch {
return defaultValue;
}
}
// Safe set
function setStorage(key, value) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch (e) {
console.warn('localStorage full:', e);
}
}
// Usage
setStorage('settings', { darkMode: true, fontSize: 16 });
const settings = getStorage('settings', { darkMode: false, fontSize: 14 });
Limits & Gotchas
- Storage limit: ~5MB per origin in most browsers
- Strings only: always JSON.stringify objects before saving
- Synchronous: reading/writing blocks the main thread — keep stored data small
- Not available in incognito: may throw in some browsers in private mode — always wrap in try/catch
- Not server-accessible: localStorage is purely client-side, never sent with HTTP requests
- Same origin only: data is scoped to the exact domain — subdomains cannot share it
⚠️ Never store sensitive data (passwords, tokens, personal data) in localStorage. It's accessible to any JavaScript on the page including third-party scripts.