JavaScript Local Storage

Introduction

Local Storage allows websites to save small amounts of data (up to ~5MB) directly in the user's browser. Data stays saved even after the user closes the browser — perfect for settings, sessions, themes, carts, or login tokens.

1. Saving Data

localStorage.setItem("username", "Kaloyan");
    

2. Loading Data

const user = localStorage.getItem("username");
console.log(user);
    

3. Removing Data

localStorage.removeItem("username");
    

4. Clearing All Local Storage

localStorage.clear();
    

5. Storing Objects (Important)

Local Storage only stores strings — so you need JSON.

// Save object
const settings = { theme: "dark", volume: 70 };
localStorage.setItem("settings", JSON.stringify(settings));

// Load object
const saved = JSON.parse(localStorage.getItem("settings"));
console.log(saved.theme);
    

6. Checking If a Value Exists

if (localStorage.getItem("token")) {
  console.log("User logged in");
}
    

7. Example: Theme Switcher

// Save theme
function setTheme(mode) {
  localStorage.setItem("theme", mode);
  document.body.dataset.theme = mode;
}

// Load theme on startup
document.body.dataset.theme = localStorage.getItem("theme") || "dark";
    

8. Expiring Local Storage (Manual Expiry)

Local Storage has no expiration, but you can make your own.

function saveWithExpiry(key, value, ttl) {
  const data = {
    value,
    expiry: Date.now() + ttl
  };
  localStorage.setItem(key, JSON.stringify(data));
}

function loadWithExpiry(key) {
  const item = JSON.parse(localStorage.getItem(key));
  if (!item) return null;
  if (Date.now() > item.expiry) {
    localStorage.removeItem(key);
    return null;
  }
  return item.value;
}
    

9. Pros and Cons

Pros:

Cons:

10. When to Use Local Storage

Summary