Application / JavaScript

JavaScript Local Storage: JSON & Error Handling

Save small application state in the browser with serialization, validation, versioning, and privacy awareness.

What you’ll learn

  • Serialize JSON data
  • Validate loaded state
  • Decide what should not be stored

Before you start

You’ll need a modern browser, a basic HTML page, and a way to inspect the browser console. Practice with sample data. The interactive guide has its own activities and browser-saved progress.

Understand the idea

localStorage stores strings by origin. Use JSON.stringify and JSON.parse for structured values.

Stored data may be old, malformed, or manually changed. Load inside try/catch and merge only validated values with defaults.

Do not store secrets or sensitive personal information. Define reset, migration, and unavailable-storage behavior.

Follow the example

const KEY = 'learning.tasks.v1';
function saveState(state) {
  localStorage.setItem(KEY, JSON.stringify(state));
}
function loadState() {
  try {
    const saved = JSON.parse(localStorage.getItem(KEY) || '{}');
    return {tasks: Array.isArray(saved.tasks) ? saved.tasks : []};
  } catch {
    return {tasks: []};
  }
}

Local storage is a convenient place for small browser preferences or practice progress. It stores strings, so serialize structured values with JSON.stringify and read them with JSON.parse. Treat saved data as untrusted input and support a safe default.

Try it yourself

Add persistence to your task app. Test first visit, valid saved state, malformed JSON, missing properties, reset, and storage failure.

Before you run the code, write down the result you expect. Change one input, test a boundary case, and explain why the output changes.

Practice this lesson in the full guide ↗

Build a small task list

Download the complete HTML practice project, open it in your browser, and change one behavior at a time. It combines form validation, safe DOM rendering, and browser storage.

Download the task list starter ↓

Common mistakes & troubleshooting

  • Wrap both reads and writes in try/catch. Private browsing, quota limits or browser policy can make storage unavailable.
  • JSON.parse can fail when a stored value is corrupted. Recover with a default state instead of blocking the application.
  • Do not store passwords, tokens or sensitive learner notes in a public example. Local storage is readable by scripts on the same origin.

Keep learning

Use your explanation to make a small feature of your own. Review the behavior before connecting it to real user data or a production application.