Reading history

JavaScript localStorage and sessionStorage Tutorial

4 min read 2 views

Learn JavaScript localStorage and sessionStorage: setItem, getItem, storing objects with JSON, a to-do list that persists, limits and security.

Ordinary JavaScript variables disappear when the page is closed or reloaded. The browser’s Web Storage API lets a site keep small amounts of data on the user’s device: a chosen theme, the items in a to-do list, a half-written form. localStorage keeps data until it is deleted, while sessionStorage keeps it only for the current tab.

In this lesson you will learn

  • Saving, reading and removing values
  • Storing arrays and objects with JSON
  • The difference between localStorage and sessionStorage
  • Building a to-do list that survives a reload
  • Limits and security rules

Saving and Reading Values

localStorage.setItem("theme", "dark");     // save
const theme = localStorage.getItem("theme"); // read: "dark"
const missing = localStorage.getItem("nope"); // null if not found

localStorage.setItem("visits", 5);
console.log(typeof localStorage.getItem("visits")); // "string"

localStorage.removeItem("theme");          // delete one key
localStorage.clear();                      // delete everything for this site
console.log(localStorage.length);          // number of saved keys
  • Storage works with key-value pairs, and both keys and values are always strings. The number 5 comes back as "5", so convert it with Number().
  • getItem() returns null for a key that does not exist, which makes defaults easy: localStorage.getItem("theme") ?? "light".
  • Each website gets its own separate storage. One site cannot read another site’s data.

The examples in this lesson are shown as code only, because the live previews on this site run in a locked-down sandbox where storage is switched off for security. Paste them into your browser’s console (F12) on any page to try them.

Storing Arrays and Objects

const settings = { fontSize: 18, language: "bn", notifications: true };

// Objects must be converted to text first
localStorage.setItem("settings", JSON.stringify(settings));

// ...and converted back when read
const saved = JSON.parse(localStorage.getItem("settings")) ?? {};
console.log(saved.fontSize + 2); // 20

// Without JSON you only get a useless string:
localStorage.setItem("broken", settings);
console.log(localStorage.getItem("broken")); // "[object Object]"

Wrap JSON.parse in try…catch if the stored text might be damaged, so a bad value cannot crash the page.

Example: A To-Do List That Remembers

const KEY = "todos";

function loadTodos() {
  try {
    return JSON.parse(localStorage.getItem(KEY)) ?? [];
  } catch {
    return [];
  }
}

function saveTodos(todos) {
  localStorage.setItem(KEY, JSON.stringify(todos));
}

let todos = loadTodos();

function addTodo(text) {
  todos.push({ id: Date.now(), text, done: false });
  saveTodos(todos);
}

function toggleTodo(id) {
  todos = todos.map((t) => (t.id === id ? { ...t, done: !t.done } : t));
  saveTodos(todos);
}

addTodo("Finish the storage lesson");
console.log(loadTodos()); // still there after a page reload

The pattern is always the same: load once at start-up, change the array in memory, and save the whole array after every change. Connect addTodo to a form’s submit event and redraw the list after each change to get a complete app.

localStorage vs sessionStorage vs Cookies

localStoragesessionStorageCookies
LastsUntil deletedUntil the tab closesUntil an expiry date
Shared between tabsYesNoYes
Sent to the serverNoNoYes, with every request
Typical sizeAbout 5 MBAbout 5 MBAbout 4 KB each

sessionStorage has exactly the same methods as localStorage.

Common Mistakes

  1. Storing objects without JSON.stringify.
  2. Forgetting values come back as strings: "5" + 1 is "51".
  3. Saving passwords, tokens or personal data. Any script on the page can read localStorage, so a single injected script could steal it.
  4. Treating it as a database. Users can clear it at any time, and it does not sync between devices.

Practice Exercises

Exercise 1. Count how many times the user has opened the page and show it in the console.

Show answer
const visits = Number(localStorage.getItem("visits") ?? 0) + 1;
localStorage.setItem("visits", visits);
console.log(`You have visited ${visits} times`);

Exercise 2. Remember a dark-mode choice: toggle a dark class on the body and restore it on load.

Show answer
if (localStorage.getItem("theme") === "dark") {
  document.body.classList.add("dark");
}
document.querySelector("#theme").addEventListener("click", () => {
  const dark = document.body.classList.toggle("dark");
  localStorage.setItem("theme", dark ? "dark" : "light");
});

classList.toggle() returns true when the class was added.

Frequently Asked Questions

How do I see what a site has stored?

Open developer tools, go to the Application tab (Storage in Firefox) and choose Local Storage. You can view, edit and delete entries there.

Is localStorage synchronous?

Yes. Reads and writes happen immediately and block the page briefly, which is fine for small data. For large amounts of data, use IndexedDB instead.

Summary

  • setItem, getItem, removeItem and clear manage stored strings.
  • Use JSON.stringify and JSON.parse for arrays and objects.
  • localStorage lasts; sessionStorage ends with the tab.
  • Never store secrets in browser storage.

Next: JavaScript Modules.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *