Objects in Storage
localStorage only stores strings. Serialize objects with JSON.stringify() before storing and parse them back with JSON.parse() on retrieval.
localStorage only stores strings. Serialize objects with JSON.stringify() before storing and parse them back with JSON.parse() on retrieval.
// Store an object
const prefs = { theme: "dark", fontSize: 16, notifications: true };
localStorage.setItem("prefs", JSON.stringify(prefs));
// Retrieve and parse
const stored = localStorage.getItem("prefs");
const prefs2 = stored ? JSON.parse(stored) : {};
// Helper with default
function getStored(key, defaultVal) {
try {
const val = localStorage.getItem(key);
return val !== null ? JSON.parse(val) : defaultVal;
} catch { return defaultVal; }
}
Always provide a fallback default value when reading from storage — the key may not exist on first use.
More in JavaScript