Zum Hauptinhalt springen
← ⚡ JavaScript & the browser·Modul C9 · Lektion 2
AufgabeSave 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
Theorie

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.

🔒

Anmelden, um zu programmieren

Theorie ist für alle offen. Editor, Live-Preview und Check werden mit 7-Tage-Gratis-Test freigeschaltet — Karte erforderlich, jederzeit kündbar.

Registrieren — Gratis-Test →

Die ersten 10 Lektionen jedes Tracks sind kostenlos. Keine Karte nötig.

← ZurückNächste Lektion →

Bekomme einen Python- oder Web-Tipp pro Tag — per E-Mail

Kurz, handgeschrieben, kein Spam. Abmelden mit einem Klick.