Himanshu SharmaSoftware engineer
Let’s talk

JavaScript · Lesson 51 of 58

localStorage

Save small amounts of data in the browser with localStorage, store objects as JSON, and handle missing or blocked storage so your page keeps working.

13 minThe DOM and eventsUpdated 14 November 2026

Awaiting technical review. This lesson is readable but not yet listed in search engines.

By the end of this lessonSave, read and remove values with localStorage, store arrays and objects with JSON, and write code that still works when storage is empty or unavailable.

Normally everything your page knows disappears when the user refreshes. Variables reset, and DOM changes vanish. After this lesson you will be able to save small pieces of data in the browser, such as a theme choice or a to-do list, and load them again next time.

What localStorage is

localStorage is a small key and value store that the browser keeps for each website. Whatever you put in it survives closing the tab and restarting the browser. It is local: it lives on that user's device, and your server never sees it unless you send it.

The methods are few:

javascript
localStorage.setItem("theme", "dark");   // save
localStorage.getItem("theme");           // "dark"
localStorage.getItem("missing");         // null
localStorage.removeItem("theme");        // delete one key
localStorage.clear();                    // delete everything for this site

Keys and values are both strings. If you save a number or a boolean it becomes text, and you get text back: setItem("count", 5) then getItem("count") returns "5". Convert with Number("5") when you need to calculate.

A related object, sessionStorage, has the same methods but forgets everything when the tab closes. Use localStorage for things that should last.

An important note about the examples here

The live editors in these lessons run your code in a sandboxed frame that is deliberately isolated from the site, and in that frame the browser blocks storage and throws an error when you touch localStorage. That is a good reason to learn the defensive style: our examples catch the error and fall back to a plain in-memory object so you can still see the logic work. Open the same code in a normal page, for example in your own file or with our HTML viewer, to see real persistence.

html
<button id="bump">Visit counter</button>
<p id="out"></p>
<script>
  // Use real storage when allowed, otherwise a temporary stand-in.
  let store;
  let persistent = true;
  try {
    store = window.localStorage;
    store.getItem("probe");
  } catch (error) {
    persistent = false;
    const memory = {};
    store = {
      getItem: key => (key in memory ? memory[key] : null),
      setItem: (key, value) => { memory[key] = String(value); }
    };
  }

  let visits = Number(store.getItem("visits") ?? 0);
  const out = document.getElementById("out");
  function show() {
    out.textContent = "Count: " + visits + (persistent ? " (saved in this browser)" : " (storage blocked here, kept in memory only)");
  }
  document.getElementById("bump").addEventListener("click", function () {
    visits = visits + 1;
    store.setItem("visits", visits);
    show();
  });
  show();
</script>

Read it in three parts: pick a store, load the saved number (falling back to 0 with ?? when the key is missing), then save after each change. In a real page you could drop the fallback and simply use localStorage.

Saving objects and arrays

Since only strings can be stored, convert other data to JSON text with JSON.stringify, and back with JSON.parse.

javascript
const settings = { theme: "dark", fontSize: 18 };
const text = JSON.stringify(settings);
console.log(text);
console.log(typeof text);
const copy = JSON.parse(text);
console.log(copy.fontSize + 2);

Running this with Node prints {"theme":"dark","fontSize":18}, then string, then 20. The same two functions turn an array of tasks into a string for saving and back into an array for use. You can inspect JSON text with our JSON formatter.

Remember that JSON cannot hold everything. Functions are dropped, and a Date comes back as a string. Keep stored data to plain values: strings, numbers, booleans, arrays and simple objects.

A safe way to read

Reading can fail in three ways: the key is missing, the stored text is not valid JSON (it may have been edited or written by an older version of your code), or storage is not available at all. Wrap it once in a small helper and use that everywhere:

javascript
function load(read, key, fallback) {
  try {
    const raw = read(key);
    return raw === null ? fallback : JSON.parse(raw);
  } catch (error) {
    return fallback;
  }
}

const fake = { good: '["a","b"]', bad: "{not json" };
const read = key => (key in fake ? fake[key] : null);
console.log(load(read, "good", []));
console.log(load(read, "bad", []));
console.log(load(read, "none", []));

Node prints [ 'a', 'b' ], then [], then []. In the browser you would pass key => localStorage.getItem(key) as the reader. The function never throws and always returns something usable.

Writes need the same care, because storage can be full or disabled:

javascript
function save(key, value) {
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch (error) {
    // storage full or blocked: carry on without saving
  }
}

A tiny to-do saver

Putting it together, here is the shape of a real page. This version keeps the data logic in one place so the page loads saved tasks on start and saves after each change:

javascript
let tasks = load(key => localStorage.getItem(key), "tasks", []);

function addTask(text) {
  tasks.push({ text, done: false });
  save("tasks", tasks);
  render();
}

The final project in this course uses exactly this pattern.

Limits and privacy

  • Size: browsers allow only a few megabytes per site. It is meant for small data.
  • Scope: values are tied to the site's origin and the browser profile. They are not shared between browsers or devices.
  • Users can clear it, and private windows often start empty, so your page must work with nothing saved.
  • Never store secrets. Any script on your page can read it, including a script that was injected through a bug. Do not keep passwords or private tokens here.
  • It is synchronous. Very large reads and writes can briefly freeze the page.
  • Tell users when you store personal data and respect privacy rules that apply to your site.

Common mistakes

  • Expecting numbers or objects back. Everything returns as a string. Parse it.
  • Saving an object directly. setItem("user", user) stores "[object Object]". Use JSON.stringify.
  • Calling JSON.parse(null) or on bad text without a guard.
  • Assuming a key exists the first time. Check for null and use a default.
  • Storing sensitive data, such as passwords.
  • Forgetting to save after changing the data, so a refresh loses the last edit.
  • Mutating the loaded value and never writing it back. Reading gives you a copy.

Exercise

Build a page with a text area and a "Save" button that stores its content under a key. On load, put any saved text back in the text area, and add a "Clear" button using removeItem. Wrap reads and writes in try and catch. Then extend it to remember a list of the last five notes using JSON.stringify and JSON.parse. Test with an empty storage and with the value {bad saved by hand.

Back to the start of this section: The DOM. Next in the course: Timers and the event loop.

Key points

  • localStorage keeps key and value pairs in the user's browser, and they stay after the page is closed.
  • Use setItem, getItem and removeItem; getItem returns null for a key that does not exist.
  • Only strings can be stored, so convert objects and arrays with JSON.stringify and JSON.parse.
  • Storage belongs to one site on one browser and is limited in size, so never keep secrets or passwords in it.
  • Wrap reads and writes in try and catch, because storage can be blocked, full, or hold corrupt data.

Check yourself

1. What does localStorage.getItem("theme") return if nothing was ever saved under that key?
2. You run localStorage.setItem("count", 5) and later read it back. What type is the result?
3. How do you store an array of tasks in localStorage?
4. Which of these should NOT be kept in localStorage?
5. Why wrap JSON.parse of stored data in try and catch?

Free tools for this lesson