HTML Web Storage (localStorage & sessionStorage)
HTML Web Storage: localStorage & sessionStorage
The Web Storage API gives web pages a simple key-value store in the browser, letting you save small amounts of data on the user's device without needing cookies or a server round-trip. It comes in two flavors: localStorage and sessionStorage, both accessed through nearly identical JavaScript methods.
localStorage vs sessionStorage
- localStorage — data persists indefinitely, even after the browser is closed and reopened, until explicitly cleared.
- sessionStorage — data lasts only for the current browser tab's session; it's cleared automatically when the tab is closed.
Both are scoped per-origin (protocol + domain + port), meaning one website cannot read another website's stored data.
Core Methods
- setItem(key, value) — stores a value under a key.
- getItem(key) — retrieves the stored value, or
nullif it doesn't exist. - removeItem(key) — deletes a single key.
- clear() — removes everything stored for that origin.
Storing Objects and Arrays
Web Storage can only store strings. To save an object or array, convert it with JSON.stringify() before storing, and parse it back with JSON.parse() when reading it.
Listening for Storage Changes
The storage event fires on other open tabs (of the same origin) whenever localStorage changes, which is useful for syncing state across multiple open tabs of the same app in real time.
Limitations
Most browsers cap Web Storage at around 5–10MB per origin, it's synchronous (which can block the main thread for large amounts of data), and it should never be used to store sensitive information like passwords or tokens, since it's accessible to any script running on the page.
Common Use Cases
Remembering a user's theme preference (dark/light mode), saving unsaved form drafts, caching API responses, storing a shopping cart, or remembering a "don't show this again" dismissal.
Press Run to execute.
Press Run to execute.
Write JavaScript that saves the user's dark-mode choice ('on' or 'off') to localStorage whenever a toggle button is clicked, and reads it back on page load to apply the correct theme immediately.
Press Run to execute.
Show expected output
Clicking the toggle stores 'on' or 'off' in localStorage under a theme key, and reloading the page reapplies the saved value.This is a self-check — compare your result with the expected output above.
Was this page helpful?