Intermediate level · Module 4: Browser Storage and Robust Forms · Lesson 1 of 3
localStorage and sessionStorage
Save data in the browser so it survives reloads, store objects as JSON and guard against missing or corrupted data.
In this lesson you will
- Read and write Web Storage
- Store and load objects safely as JSON
Key concepts
localStorage vs sessionStoragesetItem / getItemJSON in storagestorage limits and privacy
The lesson
localStorage keeps strings for a site until they are removed; sessionStorage keeps them only until the tab is closed. Both store text, so save objects with JSON.stringify and load them with JSON.parse.
Stored data can be missing (first visit), from an older version of your app or corrupted. Wrap loading in try/catch, validate the result and fall back to a sensible default.
Web Storage holds only a few megabytes and anyone using the same browser profile can read it. Never store passwords or sensitive personal data there, and remember that users may use shared computers.
Step by step
- Save the budget entries with localStorage.setItem.
- Load them on page load with getItem and JSON.parse.
- Corrupt the stored value in DevTools and handle it.
- Add a 'clear my data' button.
Practice activity
Make the to-do list from the Beginner level remember its tasks across reloads, safely.
Expected result: Tasks survive reloads, and corrupted or missing data falls back to an empty list without errors.
Check your understanding
-
What type of value does localStorage store?
Show answer
Strings only.
-
Why must loading from localStorage be guarded?
Show answer
The data may be missing, outdated or corrupted, and JSON.parse can throw.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.