Lesson 18 of 28

In progress

Course progress

JavaScript

Saving data with localStorage

Store small values in the browser, serialise objects safely, and know when storage is the wrong tool.

localStorage keeps key-value strings in the browser, survives a reload and has no server involved. It is perfect for a theme choice or a small task list, and wrong for anything sensitive or large.

What you will learn

  • Write and read strings, and serialise objects with JSON.
  • Handle quota errors and corrupted data.
  • Decide between local storage, session storage and a server.

The API is four methods

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

getItem returns null for a missing key, not undefined. Everything is stored as a string, so setItem("count", 3) stores "3", and reading it back gives a string.

Keys are shared across the whole origin, so prefix them: tin.theme, tin.tasks. A generic key such as data will collide with another script on the same site.

Objects need JSON

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

Storing an object directly produces "[object Object]", which cannot be parsed back. Always stringify on the way in.

Reading needs the same care in reverse: the key may be absent, and the stored text may be corrupted. A small helper keeps both concerns in one place.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

When writes fail

Storage can throw. Private browsing modes, disabled storage and a full quota all produce exceptions, and an unhandled one breaks the feature that triggered the write.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The usual cause is QuotaExceededError, which means the origin has hit its limit, typically around 5 MB. Handle it by telling the user that changes will not persist, rather than pretending the save worked.

Storage is per origin, not per person

Anything in localStorage is readable by any script on the same origin and remains after logout. Never store tokens, passwords, personal records or anything you would not put in a public cache.

It is also visible in DevTools and copyable, so treat it as user-editable. Validate it the same way you would validate a network response.

For data that must follow a person across devices, the server is the only option. Local storage is a convenience for this browser, not a database. It is also unencrypted, so any extension or person with access to the machine can read it: fine for a theme choice, not fine for a home address.

Changes in another tab

The storage event fires in other tabs of the same origin when a value changes. It does not fire in the tab that made the change, which is worth remembering when testing.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

sessionStorage and cookies

sessionStorage has the same API and is cleared when the tab closes, which suits a draft or a one-time flow.

Cookies are sent to the server with every request, so they are the right place for a session identifier, and the wrong place for bulk data. HttpOnly cookies cannot be read by JavaScript, which is a security feature.

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

A theme preference, end to end

JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The stored value is untrusted, so the code maps it to one of two known values instead of assigning it directly to the attribute. That small check prevents an unexpected theme name from breaking the stylesheet.

Calling JSON.parse(localStorage.getItem("x")) without a guard throws on the first visit, when the key is missing and getItem returns null. JSON.parse(null) returns null rather than throwing, but a corrupted string throws, so the helper with a fallback is still the right pattern.

Write saveTasks(tasks) and loadTasks() using one key, JSON, and a fallback to an empty array. Test loading before anything has been saved, then save two tasks and load them back.

Show solution
JavaScript
Editable. Runs in your browser.





Press Run to see the output.

The array check matters: valid JSON can still be the wrong shape, and returning an array keeps every caller from adding its own guard.

Recap

  • Storage holds strings per origin; stringify objects and prefix keys.
  • Guard both missing keys and corrupted JSON, and expect writes to fail.
  • Never store secrets; use the server for data that must follow the user.

You have finished data and asynchronous JavaScript. Next, you will use the modern syntax that makes this code shorter and clearer.

How much can localStorage hold?
About 5 MB per origin in most browsers, though the exact limit varies. It is not a place for images or large datasets.
Is localStorage synchronous?
Yes, which is why writing large values can block the main thread. Keep stored data small.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.