SyntaxStudy
Sign Up
JavaScript JSON with localStorage
JavaScript Beginner 4 min read

JSON with localStorage

JSON and localStorage

localStorage stores strings only. Use JSON.stringify() to store objects and JSON.parse() to retrieve them.

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

Wrap JSON.parse(localStorage.getItem()) in try/catch — stored data can be corrupted or from an old schema.