Skip to main content
← ⚑ JavaScript & the browserΒ·Module C9 Β· Lesson 2
TaskSave user = {name:'Anna', age:30} to localStorage under key 'user'. Read it back via JSON.parse and log got.name + ', ' + got.age. Then localStorage.removeItem('user'), read again, log 'fallback: ' + (JSON.parse(localStorage.getItem('user') || 'null') || 'no user').

Storing objects with JSON.stringify

100 XP7 min
Theory

Storage is strings only

localStorage.setItem("user", { name: "Anna" }) writes the string "[object Object]" β€” not what you want. Wrap in JSON.stringify and JSON.parse.

const user = { name: "Anna", age: 30 };
localStorage.setItem("user", JSON.stringify(user));

const got = JSON.parse(localStorage.getItem("user") || "null");
got.name; // "Anna"

Defensive read

JSON.parse(null) throws. JSON.parse("undefined") throws too. Always fall back to a safe string:

const raw = localStorage.getItem("user");
const user = raw ? JSON.parse(raw) : null;

Or use the safeParse pattern from C7-09.

Versioning

If you change the shape of stored objects, OLD data already on user machines breaks. Add a version field early:

localStorage.setItem("prefs", JSON.stringify({ v: 1, theme: "dark" }));

Then on read, check prefs.v and migrate if older.

πŸ”’

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial β€” card required, cancel anytime.

Sign up β€” free trial β†’

First 10 lessons in each track are free. No card needed for those.

← PreviousNext lesson β†’

Get one Python or web tip a day β€” by email

Short, hand-written, no spam. Unsubscribe in one click.