Přejít k hlavnímu obsahu
← ⚡ JavaScript & the browser·Modul C9 · Lekce 2
ÚkolSave 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
Teorie

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.

🔒

Zaregistruj se a začni programovat

Teorie je otevřená pro každého. Editor, živý náhled a check se odemknou s 7denní zkušební verzí zdarma — karta vyžadována, zrušíš kdykoli.

Registrace — zkušební verze zdarma →

Prvních 10 lekcí v každé trase je zdarma. Karta není potřeba.

← PředchozíDalší lekce →

Jeden tip k Pythonu nebo webu denně — e-mailem

Krátké, ručně psané, žádný spam. Odhlásit jedním klikem.