Skip to content
Guest
Learn JavaScript · Course Syllabus Show lessons
DOM & Browser APIs · 8 min read · Beginner

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:

Resilient Note Persistence Wrapper
Live Result
Console Output

No console output yet. Try calling console.log(...) in JS.

Check Your Understanding

Score: 0 / 1

1. What type of values can localStorage store directly?

Study Workspace

Finished this lesson?

Your progress is saved locally in your browser, no account needed.

Search courses, lessons, and references

Type to search across all courses, lessons, and quick references.

Press Esc to close Powered by Pagefind