Persisting State with localStorage & JSON
Save user preferences, notes, and course progress right in the browser using localStorage, JSON.stringify, and safe try/catch wrappers.
What you'll learn
- Store and read key-value strings with localStorage.setItem() and getItem()
- Serialize arrays and objects with JSON.stringify() and JSON.parse()
- Guard storage calls with try/catch for restricted or private browsing modes
localStorage lets your web app remember state across page reloads, with zero backend database! DevPath itself uses localStorage to save your completed lessons and theme preference.
Storing Objects via JSON
localStorage only stores strings. To save an object or array, convert it with JSON.stringify() on write and JSON.parse() on read:
const prefs = { theme: 'dark', fontSize: 16 };
localStorage.setItem('prefs', JSON.stringify(prefs));
const loaded = JSON.parse(localStorage.getItem('prefs') ?? '{}');
Fill-in-the-Blank Exercise
Save & Load JSON State
Serialize the bookmarks array to JSON when saving and parse it back when loading.
localStorage.setItem('bookmarks', JSON.(bookmarks));
const saved = JSON.(localStorage.getItem('bookmarks') ?? '[]');Try It Yourself
Notice how our safe storage wrapper gracefully handles sandboxed environments where localStorage may be restricted, falling back to in-memory storage without crashing:
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. What type of values can localStorage store directly?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.