Skip to main content
πŸ“œ WAYPOINT LESSON

Browser Storage: localStorage + JSON

⭐⭐ intermediate⏳ 14 min readπŸ“ Lesson 40 of 143

Remember data between visits: localStorage persists in the browser, and JSON carries structured data in and out.

Variables vanish when the page closes. localStorage gives every site a small, private key–value store that survives reloads and restarts.

The API β€” four methods

localStorage.setItem("theme", "dark"); // save a string
localStorage.getItem("theme"); // "dark" β€” or null if absent
localStorage.removeItem("theme"); // delete one key
localStorage.clear(); // delete everything for this site

Only strings are stored. Numbers, booleans, arrays, and objects must travel as text β€” that is JSON's job:

const settings = { theme: "dark", fontSize: 16 };

localStorage.setItem("settings", JSON.stringify(settings)); // object β†’ string

const raw = localStorage.getItem("settings");
const parsed = JSON.parse(raw); // string β†’ object
parsed.fontSize; // 16

Guarding against corrupted data

JSON.parse throws on invalid text. Anything in storage could be old or corrupted β€” wrap the read:

function loadSettings() {
  try {
    return JSON.parse(localStorage.getItem("settings")) ?? { theme: "light" };
  } catch {
    return { theme: "light" }; // corrupted β†’ fall back to defaults
  }
}

?? (nullish coalescing) supplies a default when the left side is null/undefined β€” perfect with getItem, which returns null for missing keys.

What it is for β€” and what it is not

Great for: preferences, theme, drafts, "remember me" UI state, small game progress.

Not for: passwords or anything sensitive (any code on the page can read it), and not for large data (a few MB at most). Real user accounts live on a server β€” localStorage is the browser's notebook, not the database.

A tiny state machine

const visits = Number(localStorage.getItem("visits") ?? "0") + 1;
localStorage.setItem("visits", String(visits));
console.log("Visit number " + visits);

Read β†’ update β†’ write back β€” the same state-and-render loop as the counter, now durable across visits.

What you learned

  • setItem/getItem/removeItem/clear
  • Storage holds strings: JSON.stringify in, JSON.parse out
  • Wrap parses in try/catch; default missing values with ??
  • Right tool for preferences and drafts β€” never for secrets

Next: programs that wait β€” asynchronous JavaScript.

⚑ Now practice

Ready to Code
Browser Storage: localStorage + JSON β€” PracticeHands-on practice for β€œBrowser Storage: localStorage + JSON”: apply what you just learned in js-local-storage.
1 challenge Β· Β· ~10 min
State That SurvivesPersistence with localStorage: save objects as JSON, load them back safely, and handle corrupt data like a professional.
2 challenges Β· Β· ~12 min