JSON and localStorage
localStorage stores strings only. Use JSON.stringify() to store objects and JSON.parse() to retrieve them.
localStorage stores strings only. Use JSON.stringify() to store objects and JSON.parse() to retrieve them.
// Store object in localStorage
const settings = { theme: "dark", fontSize: 16 };
localStorage.setItem("settings", JSON.stringify(settings));
// Retrieve and parse
const stored = localStorage.getItem("settings");
const settings2 = stored ? JSON.parse(stored) : { theme: "light" };
// Helper functions
const storage = {
set: (key, val) => localStorage.setItem(key, JSON.stringify(val)),
get: (key, fallback = null) => {
try { return JSON.parse(localStorage.getItem(key)) ?? fallback; }
catch { return fallback; }
},
};
Wrap JSON.parse(localStorage.getItem()) in try/catch — stored data can be corrupted or from an old schema.
More in JavaScript