Skip to content
Kuza Ndoto Academy

Local Storage

Beginner → IntermediateChapter 5 · Page 27 of 324 min readUpdated 15 Nov 2026

Everything your script puts on the page disappears when the user reloads or closes the tab. localStorage lets you keep small amounts of data in the browser between visits: a theme choice, a draft message, a shopping cart, a to-do list. It is simple to use, with one important rule: it only stores strings.

The basic methods

localStorage is a store of key → value pairs that belongs to your website (strictly, to its origin: protocol, domain and port). Other sites can't read it, and it stays until your code or the user removes it.

MethodWhat it does
localStorage.setItem(key, value)Saves a value under a key (replacing any old value)
localStorage.getItem(key)Returns the value, or null if the key doesn't exist
localStorage.removeItem(key)Deletes one key
localStorage.clear()Deletes everything your site saved
localStorage.length / key(i)How many keys there are / the name of key number i

Starting with empty storage for this site:

localStorage.setItem("theme", "dark");
localStorage.setItem("county", "Nakuru");

console.log(localStorage.getItem("theme"));
console.log(localStorage.getItem("missing"));
console.log(localStorage.length);

localStorage.removeItem("county");
console.log(localStorage.length);
dark null 2 1

Reload the page and getItem("theme") still returns "dark". You can inspect and edit the stored values in DevTools: Application tab → Local Storage (Chrome/Edge) or Storage tab (Firefox).

Strings only

Whatever you store is converted to a string first. Numbers come back as text, and objects turn into the useless string "[object Object]":

localStorage.setItem("score", 10);
const score = localStorage.getItem("score");
console.log(score, typeof score);
console.log(score + 5);

localStorage.setItem("user", { name: "Baraka" });
console.log(localStorage.getItem("user"));
10 string 105 [object Object]
localStorage (one store per origin) keyvalue (always a string) theme"dark" visits"3" (text, not the number 3) cart'[{"item":"Unga","qty":2}]' setItem(key, value) getItem(key) null if missing
Figure 1. Every value is a string. Numbers need Number() when read back, and arrays or objects must be stored as JSON.

Storing objects and arrays with JSON

The fix is JSON: stringify when saving and parse when loading.

const cart = [
  { item: "Unga", qty: 2 },
  { item: "Sukari", qty: 1 }
];
localStorage.setItem("cart", JSON.stringify(cart));

const saved = JSON.parse(localStorage.getItem("cart"));
console.log(saved[0].item, saved.length);
Unga 2

When loading, the key might not exist yet (a first-time visitor). JSON.parse(null) returns null, so a fallback with ?? handles that neatly:

const savedCart = JSON.parse(localStorage.getItem("cart")) ?? [];

And for numbers, convert with Number(). This visit counter works on the first visit too, because Number(null) is 0:

let visits = Number(localStorage.getItem("visits")) || 0;
visits++;
localStorage.setItem("visits", visits);
console.log(`Visit number ${visits}`);

On a first visit (refresh to see it count up):

Visit number 1

localStorage vs sessionStorage

sessionStorage has exactly the same methods, but its data only lasts while the tab is open.

localStoragesessionStorage
Survives reloadYesYes
Survives closing the browserYesNo
Shared between tabs of the same siteYesNo, one per tab
Good forPreferences, carts, saved listsA multi-step form in progress

Limits and good practice

  • Small data only. Browsers allow roughly 5 MB per origin. setItem throws an error when storage is full, and some private or sandboxed windows block storage entirely, so wrap writes in try/catch in real apps.
  • It is synchronous. Every read and write blocks the page briefly. That is fine for small values; avoid storing huge amounts.
  • The user controls it. They can view, edit or clear it at any time, so treat loaded data as untrusted and parse it safely.
Warning

Never store passwords, M-Pesa PINs, ID numbers or secret tokens in localStorage. Any script running on your page, including a malicious one injected through an XSS bug, can read everything in it.

Try it: remember the theme and a note

This page saves your dark-mode choice and whatever you type. The preview on this site runs in a locked-down sandbox that blocks storage, so the code catches that error and keeps working without saving. Copy the code into a .html file and open it in your browser to see it remember things after a reload.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: sans-serif; padding: 10px; }
    body.dark { background: #1f2d42; color: white; }
    textarea { width: 100%; height: 80px; }
  </style>
</head>
<body>
  <button id="theme">Toggle dark mode</button>
  <h3>My notes</h3>
  <textarea id="notes" placeholder="Type something, then reload the page"></textarea>
  <p id="info"></p>

  <script>
    const notes = document.querySelector("#notes");
    const info = document.querySelector("#info");

    function load(key) {
      try {
        return localStorage.getItem(key);
      } catch {
        info.textContent = "Storage is blocked in this preview. Open the file in your own browser to test saving.";
        return null;
      }
    }

    function save(key, value) {
      try {
        localStorage.setItem(key, value);
      } catch {
        // storage unavailable: the page still works, it just won't remember
      }
    }

    // Restore what was saved last time
    if (load("theme") === "dark") document.body.classList.add("dark");
    notes.value = load("notes") ?? "";

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

    notes.addEventListener("input", () => save("notes", notes.value));
  </script>
</body>
</html>

Key points

  • localStorage keeps key → value pairs per origin, even after the browser closes.
  • setItem, getItem (returns null if missing), removeItem and clear are all you need.
  • Values are always strings: use JSON.stringify/JSON.parse for objects and Number() for numbers.
  • Keep it small, wrap it in try/catch, and never store secrets in it.
Up next · New chapter: Modern JavaScriptError Handlingtry, catch, finally and throwing errors.
→

Tip: use the ← and → keys to move between pages.