The DOM & EventsExtra· 35 min read

Web Storage: localStorage & sessionStorage

Save data right in the browser so it survives a refresh — the simple trick behind remembered to-do lists, carts and dark-mode settings.

What you will learn

  • Save and read values with localStorage
  • Store objects by combining it with JSON
  • Tell localStorage and sessionStorage apart

A tiny notebook inside the browser

Normally, every variable in your JavaScript vanishes the moment the page reloads. Web Storage gives you a small notebook inside the browser where you can write values that survive a refresh — and even survive closing the tab. It is how a to-do app remembers your tasks and a site remembers you chose dark mode.

The main tool is localStorage. It has just two everyday commands: setItem(key, value) to save, and getItem(key) to read back. You give each value a key (a name) so you can find it again — exactly like a labelled box.

Save a name that survives a refresh
<input id="name" placeholder="Type your name">
<button id="save">Save</button>
<p id="greet"></p>

<script>
  // On load: read any previously saved name and greet
  const saved = localStorage.getItem("username");
  if (saved) document.getElementById("greet").textContent = "Welcome back, " + saved + "!";

  document.getElementById("save").addEventListener("click", function () {
    const value = document.getElementById("name").value;
    localStorage.setItem("username", value);          // save it
    document.getElementById("greet").textContent = "Saved! Now refresh the page.";
  });
</script>
Live preview

Walk through what happens:

  1. When the page loads, localStorage.getItem("username") looks for a value saved under the key "username".
  2. The very first time, nothing is saved yet, so it returns null and we skip the greeting.
  3. You type a name and click Save: localStorage.setItem("username", value) writes it into the browser’s notebook.
  4. Now refresh the page. This time getItem("username") finds your saved name and greets you with it.
  5. The value stays even if you close the tab and come back tomorrow — that is the whole point of localStorage.

Note: Output: First visit: (no greeting) → type "Asha", click Save → "Saved! Now refresh the page." After refresh: Welcome back, Asha!

Storage only holds text — so use JSON for objects

There is one rule to remember: Web Storage can only hold strings (plain text). If you try to save an object or array directly, you get back the useless text "[object Object]". The fix is the JSON pair you already know: JSON.stringify to save, JSON.parse to read back.

Store an object with JSON.stringify / JSON.parse
<script>
  const cart = { items: ["Book", "Pen"], total: 350 };

  // Save: turn the object into text first
  localStorage.setItem("cart", JSON.stringify(cart));

  // Read: turn the text back into a real object
  const back = JSON.parse(localStorage.getItem("cart"));
  document.write("Items: " + back.items.join(", ") + "<br>");
  document.write("Total: " + back.total);
</script>
Live preview

JSON.stringify(cart) flattens the object into the text {"items":["Book","Pen"],"total":350}, which Web Storage is happy to hold. To use it again, JSON.parse(...) rebuilds a real object from that text, so back.items and back.total work just like normal object properties.

Note: Output: Items: Book, Pen Total: 350

Watch out: Save the string, not the raw object. localStorage.setItem("cart", cart) (no stringify) would store the literal text "[object Object]" and lose your data. Always JSON.stringify on the way in and JSON.parse on the way out.

localStorage vs sessionStorage

There are two versions, used in exactly the same way (same setItem/getItem). The only difference is how long the data lasts.

StoreLasts untilUse for
localStorageYou delete it (survives refresh AND closing the browser)To-do lists, cart, theme choice
sessionStorageYou close the tabOne-visit data, like a multi-step form in progress
  • setItem(key, value) — save a value under a name.
  • getItem(key) — read it back (returns null if not found).
  • removeItem(key) — delete one value.
  • clear() — wipe everything for this site.

Tip: You can SEE your stored data: open dev tools (F12) → Application tab → Local Storage. Watching values appear there as you save is a great way to understand what is happening.

Q. You want to save an array in localStorage. What must you do first?

Answer: Web Storage only holds strings, so call JSON.stringify before setItem, and JSON.parse after getItem to rebuild the array.

✍️ Practice

  1. Save a theme choice ("dark" or "light") in localStorage and apply it on page load.
  2. Store an array of three favourite foods using JSON.stringify, then read it back with JSON.parse.

🏠 Homework

  1. Add localStorage saving to your To-Do project so tasks remain after a refresh: save the list on every change, and load it when the page opens.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →