Saltar al contenido principal
← ⚡ JavaScript & the browser·Módulo C9 · Lección 2
TareaSave 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
Teoría

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.

🔒

Regístrate para empezar a programar

La teoría está abierta a todos. El editor, la vista previa y el check se desbloquean con una prueba gratis de 7 días — se requiere tarjeta, cancela cuando quieras.

Registrarse — prueba gratis →

Las primeras 10 lecciones de cada ruta son gratis. No se necesita tarjeta.

← AnteriorSiguiente lección →

Recibe un consejo de Python o web al día — por email

Corto, escrito a mano, sin spam. Anula la suscripción en un clic.