localStorage, JSON & safe defaults
Remember things with localStorage
Lesson 10 of 20 · 12 min · Module 3: State, storage and accessibility
A note that disappears on reload is frustrating. localStorage keeps small amounts of data in the browser between visits, without any server.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Save and load strings with localStorage
- Store objects as JSON
- Fall back to defaults when data is missing or damaged
The idea
localStorage.setItem(key, value) saves a string and getItem(key) reads it back, or returns null when nothing is saved. Objects must be turned into text with JSON.stringify and back with JSON.parse. Saved data can be missing or damaged, so always fall back to sensible defaults.
localStorage.setItem('ct-theme', 'dark');
const theme = localStorage.getItem('ct-theme') ?? 'light';
localStorage.setItem('ct-prefs', JSON.stringify({ sound: false }));
01Strings only
localStorage converts everything to text. Saving an object directly stores the useless string [object Object], so always stringify objects and arrays.
localStorage.setItem('x', { a: 1 });
console.log(localStorage.getItem('x'));[object Object]02Expect the unexpected
People clear their storage, older versions of your page saved different shapes, and browser extensions sometimes change values. try/catch around JSON.parse and a default value keep the page working whatever is stored.
03Know the limits
Storage is per site and per browser, holds a few megabytes, and is readable by any script on the page. Never store passwords or tokens there, and use a server when data must follow people across devices.
Your turn
ct-note into #note, and save the note on every input. 2) Settings are saved as JSON under ct-settings, such as {"large":true}. Load them safely: missing or damaged data means { large: false }. Apply them by ticking #large and giving #note the class is-large. When the checkbox changes, save the new settings and apply them.What the checks look for
- Typing saves the note
- A saved note comes back
- Large text is saved as JSON and applied
- Saved settings are applied on load
- Damaged settings do not break the page
- With nothing saved, the defaults apply
Take this with you
Save as JSON, load with try/catch, and always have a default.
Go a little further
Save the time of the last edit and show "Saved at 14:05" under the note.