Every web page you build eventually needs to remember something between visits — a theme preference, a saved draft, items in a cart. JavaScript gives you two simple, built-in tools for this: localStorage and sessionStorage. Both let you save key-value pairs directly in the browser, with no server or database required.
They share the exact same API, so once you learn one, you know both. The only real difference is how long the data sticks around.
Basic Syntax: setItem, getItem, removeItem
// Save a value
localStorage.setItem("username", "alex");
// Read it back
const name = localStorage.getItem("username");
console.log(name);
// Remove a single key
localStorage.removeItem("username");
// Wipe everything this page stored
localStorage.clear();
Output:
alex
Every value is stored as a string. If you try to save a number or boolean directly, it gets silently converted to text — localStorage.setItem("count", 5) actually stores "5".
Storing Objects and Arrays
Since storage only holds strings, you can't save an object or array directly. The standard pattern is to convert it to a JSON string with JSON.stringify() before saving, and parse it back with JSON.parse() when reading.
const user = { name: "Alex", loggedIn: true, visits: 4 };
// Save the object
localStorage.setItem("user", JSON.stringify(user));
// Read it back as a real object again
const saved = JSON.parse(localStorage.getItem("user"));
console.log(saved.name, saved.visits);
Output:
Alex 4
localStorage vs sessionStorage
localStorage has no expiration — data stays until you explicitly remove it or the user clears their browser data, even after closing the tab or restarting the browser. sessionStorage uses the identical API but only lives for the current browser tab: close that tab, and it's gone. Opening the same site in a new tab starts with empty sessionStorage, even though it would share the same localStorage.
A good rule of thumb: use localStorage for things that should persist across visits (a saved theme, a remembered login), and sessionStorage for things that only matter during the current session (a multi-step form's progress, a one-time dismissed banner).
Both APIs are synchronous and have a storage limit (typically around 5-10MB per origin), so they're meant for small amounts of data, not as a replacement for a real database. If you're learning JavaScript objects alongside this, storage is one of the most practical places you'll use them day to day.
