JavaScriptLesson 17 of 18

Local Storage

LocalStorage is a small storage space built into the browser. It keeps data as text, and the data survives page reloads and even browser restarts. When a visitor comes back tomorrow, the data is still there. That makes it the right tool for remembering names, theme choices, and small settings.

LocalStorage is a small storage space built into the browser. It keeps data as text, and the data survives page reloads and even browser restarts. When a visitor comes back tomorrow, the data is still there. That makes it the right tool for remembering names, theme choices, and small settings.

The API is two methods. localStorage.setItem("key", "value") stores data, and localStorage.getItem("key") reads it back. Both keys and values are strings. The data belongs to one origin, meaning one site cannot read another site storage, and it stays on the same browser and computer.

Because storage only takes strings, storing an object directly saves "[object Object]". Convert it first with JSON.stringify and read it back with JSON.parse. Two other things to know: storage is limited to about 5 MB per site, and reading a key that was never set returns null, so always check the result before using it.

Storing objects with JSON

To save an object, stringify it first, then parse it when you read it back. Wrap both in a try and catch, because some browsers block storage in private mode, and a blocked write throws an error that would otherwise stop your script.

JS
const user = { name: "Ada", age: 36 };
localStorage.setItem("user", JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem("user"));

Removing data

removeItem deletes a single key, and clear empties everything your site stored. Use removeItem when a user logs out or resets a preference. Data you store stays until you remove it or the visitor clears browser data.

JS
localStorage.removeItem("theme");
localStorage.clear();

Syntax

JS
localStorage.setItem("name", "Ada");
const saved = localStorage.getItem("name");

localStorage Only Stores Strings

localStorage.setItem("obj", {a:1}) stores "[object Object]" — use JSON.stringify.

JS
localStorage.setItem("k", JSON.stringify(obj))

Good to know

  • localStorage keeps data after the page closes, per browser and site.
  • Only strings are stored; JSON.stringify handles objects.
  • A missing key returns null, so check before you use it.
  • removeItem deletes one key; clear wipes everything.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground