Skip to content

JavaScript Tutorial Browser Storage

Saving, Reading and Removing Data in localStorage

Lesson 136 of 258 2 min read By Deepak Paswan Updated Oct 4, 2026

The Storage API has just a handful of methods.

MethodDoes
setItem(key, value)saves (or overwrites) a value
getItem(key)reads a value, or null if missing
removeItem(key)deletes one key
clear()deletes everything for this site
key(index)name of the key at a position
lengthhow many items are stored
script.js
JS
localStorage.setItem("name", "Maya");
localStorage.setItem("city", "Pune");

console.log(localStorage.getItem("name"));    // → Maya
console.log(localStorage.getItem("missing")); // → null
console.log(localStorage.length);             // → 2

localStorage.removeItem("city");
console.log(localStorage.getItem("city"));    // → null

localStorage.clear();
console.log(localStorage.length);             // → 0

Handle a missing value

getItem returns null when the key does not exist. Use ?? for a default.

script.js
JS
const theme = localStorage.getItem("theme") ?? "light";
console.log(theme); // → light

Example: a theme that remembers

index.html
HTML
<style>
  body.dark { background: #1c1b1f; color: #eee; }
</style>
<button id="toggle">Toggle theme</button>
<script>
  const body = document.body;

  // apply the saved choice when the page loads
  if (localStorage.getItem("theme") === "dark") {
    body.classList.add("dark");
  }

  document.querySelector("#toggle").addEventListener("click", () => {
    const isDark = body.classList.toggle("dark");
    localStorage.setItem("theme", isDark ? "dark" : "light");
  });
</script>

On a real page, reload after toggling and the theme stays. (Here, the editor keeps storage for one run only.)

Other ways to read keys

script.js
JS
localStorage.setItem("a", "1");
localStorage.setItem("b", "2");

for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  console.log(key, localStorage.getItem(key));
}

You can also use property syntax (localStorage.theme = "dark"), but the methods are safer: a key like length would clash with the real property.

Namespacing keys

Many apps share one origin, such as several pages on the same site. Use a prefix to avoid clashes:

script.js
JS
localStorage.setItem("notes-app:draft", text);

Errors can happen

Storage can be unavailable (private mode in some browsers, blocked by settings) or full. Wrap writes you care about in try...catch, as shown in Storage Limits.

lightbulb
Reading often
getItem is quick, but do not read and write on every keystroke of a fast event. Save when the user pauses (see Debouncing) or leaves the field.