SyntaxStudy
Sign Up
JavaScript Storing Objects with JSON
JavaScript Beginner 4 min read

Storing Objects with JSON

Objects in Storage

localStorage only stores strings. Serialize objects with JSON.stringify() before storing and parse them back with JSON.parse() on retrieval.

Example
// 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; }
}
Pro Tip

Always provide a fallback default value when reading from storage — the key may not exist on first use.