JavaScriptBeginner

JavaScript Browser Storage: localStorage and sessionStorage

Learn how to save, read, update and remove browser data with localStorage, sessionStorage and JSON.

All JavaScript lessons

What you will learn

Sometimes a website needs to remember something after the page is refreshed. For example, it may remember a theme choice, a saved name, a cart preference or a small setting.

The browser provides Web Storage for this purpose. In this lesson you will learn localStorage and sessionStorage, how to save and read values, how to remove data, and how to store objects and arrays with JSON.

The concept

There are two common storage objects:

Storage Data remains
localStorage After page refreshes and browser restarts, until the data is removed or browser storage is cleared
sessionStorage For the current browser tab/session; it is cleared when that page session ends

Both use a simple key-value system.

localStorage.setItem("name", "Riya");

Here:

key   = name
value = Riya

localStorage.setItem()

Use setItem() to save a value.

localStorage.setItem("username", "Riya");
localStorage.setItem("theme", "dark");

You can save numbers too, but they are stored as strings:

localStorage.setItem("age", 25);

Later:

const age = localStorage.getItem("age");

console.log(age);
console.log(typeof age); // "string"

If you need a number:

const age = Number(localStorage.getItem("age"));

Tip: Web Storage stores values as strings. Objects and arrays need JSON conversion.

localStorage.getItem()

Read a saved value:

const username = localStorage.getItem("username");

console.log(username);

If the key does not exist:

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

the result is:

null

You can handle that:

const username = localStorage.getItem("username");

if (username === null) {
  console.log("No username saved.");
} else {
  console.log("Welcome, " + username);
}

removeItem()

Remove one key:

localStorage.removeItem("username");

This removes only username. Other stored values remain.

clear()

Remove everything stored for the current origin:

localStorage.clear();

Be careful with clear() because it removes all localStorage entries belonging to that origin, including entries created by other parts of your site.

Updating a value

There is no separate updateItem() method.

Call setItem() again with the same key:

localStorage.setItem("theme", "light");
localStorage.setItem("theme", "dark");

The second call replaces the first value.

sessionStorage

sessionStorage has a similar API:

sessionStorage.setItem("step", "2");

const step = sessionStorage.getItem("step");

console.log(step);

You can also remove values:

sessionStorage.removeItem("step");

or clear the storage:

sessionStorage.clear();

The biggest practical difference is lifetime.

Example

A theme preference might use:

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

A temporary checkout step might use:

sessionStorage.setItem("checkoutStep", "2");

Why objects do not work directly

Suppose you try:

const user = {
  name: "Riya",
  age: 20
};

localStorage.setItem("user", user);

The browser stores the value as text. The object is not preserved as a JavaScript object.

You may see:

[object Object]

Use JSON instead.

Store objects with JSON

Convert the object to a string:

const user = {
  name: "Riya",
  age: 20,
  city: "Delhi"
};

localStorage.setItem("user", JSON.stringify(user));

Read it back:

const savedUser = localStorage.getItem("user");

const user = JSON.parse(savedUser);

console.log(user.name);
console.log(user.age);

The flow is:

JavaScript object
      ↓
JSON.stringify()
      ↓
string in storage
      ↓
JSON.parse()
      ↓
JavaScript object

Store arrays with JSON

The same idea works for arrays.

const skills = ["HTML", "CSS", "JavaScript"];

localStorage.setItem("skills", JSON.stringify(skills));

Read it:

const savedSkills = localStorage.getItem("skills");

const skills = JSON.parse(savedSkills);

console.log(skills);
console.log(skills[0]);

A safer JSON read

JSON.parse() throws an error if the stored text is not valid JSON.

A simple safe pattern:

const saved = localStorage.getItem("user");

if (saved !== null) {
  try {
    const user = JSON.parse(saved);
    console.log(user);
  } catch (error) {
    console.log("Saved user data is invalid.");
  }
}

For simple projects, the normal JSON.parse() pattern is usually enough, but understanding this failure case is useful.

Real use case: remember a theme

HTML:

<button id="theme-btn">Toggle Theme</button>

JavaScript:

const button = document.getElementById("theme-btn");

button.addEventListener("click", function () {
  const currentTheme = localStorage.getItem("theme");

  const newTheme = currentTheme === "dark"
    ? "light"
    : "dark";

  localStorage.setItem("theme", newTheme);

  document.body.dataset.theme = newTheme;
});

When the page loads, restore the saved theme:

const savedTheme = localStorage.getItem("theme");

if (savedTheme) {
  document.body.dataset.theme = savedTheme;
}

This is a common real-world use case for localStorage.

Real use case: save a draft

A user may type a long message and accidentally refresh the page.

You can save a draft:

const message = document.getElementById("message");

message.addEventListener("input", function () {
  localStorage.setItem("draft", message.value);
});

Restore it:

const savedDraft = localStorage.getItem("draft");

if (savedDraft !== null) {
  message.value = savedDraft;
}

This is useful for forms, notes and editors.

Storage belongs to an origin

Storage is associated with the site’s origin, which is roughly the combination of scheme, host and port.

For example, data stored by one website is not normally available to a completely different origin.

This is an important security and privacy boundary.

Storage is not a database

localStorage is useful for small pieces of client-side data, but it is not a replacement for a database.

Do not use it as the main place for:

  • large application datasets
  • sensitive server-side records
  • passwords
  • authentication secrets that must be protected from JavaScript access

Web Storage is accessible to JavaScript running on the page. If an attacker can execute malicious JavaScript in your origin, stored data can potentially be read.

Common mistakes

  • Forgetting that stored values are strings. Convert numbers and use JSON for objects/arrays.
  • Calling JSON.parse(null) without thinking about the missing-key case. Check whether the value exists.
  • Using clear() when you only need to remove one value. Prefer removeItem().
  • Saving passwords or sensitive secrets in localStorage. Web Storage is not a secure secret store.
  • Expecting sessionStorage to behave exactly like localStorage. Its lifetime is tied to the page session/tab context.
  • Using localStorage for large amounts of data. It is intended for relatively small client-side storage.
  • Forgetting that browser storage can be cleared by the user or browser policies. Never treat it as guaranteed permanent storage.
  • Storing an object directly. Use JSON.stringify() first.

Practice

  1. Save a username with localStorage and display it after refreshing the page.
  2. Add a button that removes only the username.
  3. Store a selected theme and restore it when the page loads.
  4. Store an array of three skills using JSON.
  5. Store a user object with name, age and city using JSON.
  6. Use sessionStorage to remember the current step of a multi-step form.
  7. Challenge: Build a notes app that automatically saves the current note to localStorage.
  8. Challenge: Add a “Clear saved data” button that removes only the keys your app created.

Recap

  • localStorage stores small key-value data that can remain after refreshes and browser restarts.
  • sessionStorage stores data for the current page session/tab context.
  • Use setItem() to save, getItem() to read, removeItem() to remove one key and clear() to remove all storage for the origin.
  • Web Storage stores strings.
  • Use JSON.stringify() to store objects/arrays and JSON.parse() to read them back.
  • Storage is useful for preferences and small client-side data, not as a database or secure secret store.