How to Use localStorage in JavaScript: Save, Read and Delete Data
Every web app needs to remember small things between page loads: a theme preference, a draft form, the contents of a shopping cart, or the last page a user visited. When that data only needs to live in the browser and does not need a server or a login, localStorage is the simplest tool for the job. The localstorage javascript API is built into every modern browser, needs no library, and stores key-value pairs that survive closing and reopening the browser. Learning its four core methods takes minutes, and using them well can make a site feel noticeably more polished.
This guide covers saving, reading, updating, and deleting data, storing objects and arrays with JSON, looping over stored keys, and recognising the limits and security rules that govern what belongs in localStorage and what does not. The storage limit is roughly 5 to 10 megabytes per origin depending on the browser, which is plenty for preferences and small state but not for files or large datasets. Data is scoped per origin, meaning the protocol, domain, and port together, so storage for one site is never visible to another. If you also send data to a server, combine these ideas with our Fetch API examples so local state and remote state stay in sync deliberately rather than by accident.
The Four Core Methods: setItem, getItem, removeItem, clear
localStorage works like a simple dictionary. You save a value under a string key with setItem, read it back with getItem, delete a single entry with removeItem, and wipe everything for your origin with clear. All keys and values are strings. If you pass a number or boolean, JavaScript converts it to a string for you, which is convenient but important to remember when reading values back.
// Save data
localStorage.setItem("username", "haseeb");
localStorage.setItem("theme", "dark");
// Read data
const username = localStorage.getItem("username");
console.log(username); // "haseeb"
// Read a missing key
const missing = localStorage.getItem("nickname");
console.log(missing); // null
// Delete one item
localStorage.removeItem("theme");
// Delete everything for this site
// localStorage.clear();
Each line does exactly one job. setItem takes the key first and the value second; calling it again with the same key overwrites the previous value, which is how updates work. getItem returns the stored string, or null if the key was never set or was removed. Checking for null is the standard way to detect a first visit or a missing preference. removeItem deletes just one key and does nothing harmful if the key does not exist. clear is the blunt instrument that removes every key for the site, including keys written by other features or libraries, so use it sparingly and prefer targeted removal in most code. We left clear commented out in the snippet because running it while testing surprises people by wiping unrelated saved state.
Storing Objects and Arrays With JSON
Since localStorage only stores strings, objects and arrays must be converted before saving and parsed after reading. JSON.stringify turns a value into a JSON string, and JSON.parse turns that string back into a live value. This pair of methods is the single most important technique in this whole guide, because almost all real data is structured.
const cart = [
{ id: 1, name: "Keyboard", qty: 1 },
{ id: 2, name: "Mouse", qty: 2 }
];
// Save the array
localStorage.setItem("cart", JSON.stringify(cart));
// Read it back
const savedCart = JSON.parse(localStorage.getItem("cart"));
console.log(savedCart.length); // 2
console.log(savedCart[0].name); // "Keyboard"
// Save a settings object
const settings = { theme: "dark", fontSize: 16, showSidebar: true };
localStorage.setItem("settings", JSON.stringify(settings));
The flow is always the same three steps: build a normal JavaScript value, stringify it when saving, and parse it when loading. After parsing, savedCart is a genuine array again, so methods like length, indexing, and the array tools from our JavaScript array methods cheat sheet all work on it. One defensive detail matters here: if the key is missing, getItem returns null and JSON.parse(null) returns null rather than throwing, but if the stored string is corrupted, JSON.parse will throw. The next section shows a safe helper that handles both cases.
A Safe Helper for Reading JSON
function loadJSON(key, fallback) {
try {
const raw = localStorage.getItem(key);
if (raw === null) {
return fallback;
}
return JSON.parse(raw);
} catch (error) {
console.error("Could not read", key, error.message);
return fallback;
}
}
const cartItems = loadJSON("cart", []);
const preferences = loadJSON("settings", { theme: "light" });
console.log(cartItems, preferences);
This helper wraps the read in a try and catch and accepts a fallback value to return when nothing is stored or parsing fails. Passing an empty array as the fallback for a cart means the rest of your code can always treat the result as an array and call methods on it without extra checks. Passing a default settings object means the interface always has a theme to apply. Writing one small helper like this and using it everywhere is far more reliable than scattering bare JSON.parse calls through a codebase, each with slightly different error behaviour.
Practical Example: Remembering a Theme Preference
A dark and light theme toggle is the classic localStorage demo because it shows the full cycle: read the saved choice on load, apply it, and save every new choice. The example below uses a data-theme attribute on the document element, which CSS can target to switch colours, similar to the variable-driven theming described in our CSS variables guide.
const savedTheme = localStorage.getItem("theme") || "light";
document.documentElement.setAttribute("data-theme", savedTheme);
const toggleButton = document.querySelector("#theme-toggle");
toggleButton.addEventListener("click", () => {
const current = document.documentElement.getAttribute("data-theme");
const next = current === "dark" ? "light" : "dark";
document.documentElement.setAttribute("data-theme", next);
localStorage.setItem("theme", next);
});
On page load, the code reads the saved theme and falls back to “light” with the logical OR operator when nothing is stored yet, then applies it immediately so the page renders in the right theme without a flash of the wrong colours. Placing this snippet early, ideally in the head or at the very start of the body script, avoids that flash. The click handler reads the current theme, flips it to the opposite value, updates the attribute so the change is visible instantly, and saves the new value so the choice persists. Three lines of storage code turn a throwaway toggle into a remembered preference, which is exactly the kind of detail users expect from a finished product.
Practical Example: Saving a Form Draft
Losing a long form because of an accidental refresh is frustrating, and localStorage can prevent it with very little code. The pattern saves field values as the user types and restores them on load, then clears the draft once the form is successfully submitted. To avoid running storage writes on every keystroke, this is a perfect place for the timing pattern from our debounce and throttle guide.
const nameInput = document.querySelector("#fullname");
const messageInput = document.querySelector("#message");
// Restore the draft on load
nameInput.value = localStorage.getItem("draft-name") || "";
messageInput.value = localStorage.getItem("draft-message") || "";
// Save as the user types
nameInput.addEventListener("input", () => {
localStorage.setItem("draft-name", nameInput.value);
});
messageInput.addEventListener("input", () => {
localStorage.setItem("draft-message", messageInput.value);
});
// Clear the draft after a successful submit
document.querySelector("#contact-form").addEventListener("submit", () => {
localStorage.removeItem("draft-name");
localStorage.removeItem("draft-message");
});
The restore step runs first: each input is filled from storage, or set to an empty string when no draft exists, so the assignments never produce the text “null” in a field. The input listeners then save on every change; for two short fields this is cheap, though for a large editor you would debounce the save. Finally, the submit handler removes both draft keys so the next visit starts with a clean form instead of resurrecting an already-sent message. Forgetting that cleanup step is the most common draft bug. Use clear, prefixed key names like “draft-name” so drafts never collide with settings or cart keys from other features.
Looping Over Keys and Checking Storage Length
Occasionally you need to see everything stored for your site, for a settings page, a debug view, or a migration. localStorage exposes a length property counting the keys, and a key(index) method that returns the key name at a position. Together they let you iterate without knowing key names in advance.
console.log("Stored keys:", localStorage.length);
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
const value = localStorage.getItem(key);
console.log(key, "=", value);
}
// Remove all keys that start with "draft-"
const keysToRemove = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key.startsWith("draft-")) {
keysToRemove.push(key);
}
}
keysToRemove.forEach((key) => localStorage.removeItem(key));
The first loop prints every key and value, which is also a quick way to inspect storage while debugging, alongside the Application tab in browser developer tools. The second part shows an important subtlety: you should not remove keys while looping forward over the same storage, because removing an item shifts the indexes of the remaining keys and you will skip some. Collecting the matching keys into an array first, then removing them afterwards, avoids that trap. This collect-then-act approach is a useful general habit whenever you modify a collection you are iterating.
localStorage vs sessionStorage vs Cookies
Browsers offer three common storage options, and picking the right one avoids confusion. localStorage persists until explicitly deleted and is shared across all tabs of the same origin. sessionStorage has an identical API but lasts only for the life of the tab or session; closing the tab discards it, and each tab gets its own separate storage. That makes sessionStorage a good fit for one-off flows like a multi-step checkout where data should not linger. Cookies are the oldest option, much smaller at around 4 kilobytes each, and they are sent to the server with every request, which makes them suitable for session identifiers managed by the server but wasteful for purely client-side preferences. A practical rule: preferences and client-only state belong in localStorage, temporary per-tab state belongs in sessionStorage, and anything the server must read on each request belongs in a cookie set by the server.
Limits, Errors, and Security Rules
Three constraints shape responsible localStorage use. First, size: when storage is full, setItem throws a quota error, so code that saves large or user-controlled data should wrap saves in try and catch and be ready to trim old entries. Second, availability: in private browsing modes or with storage disabled, even touching localStorage can throw, which is another reason the safe helper pattern matters. Third, and most important, security: never store passwords, payment details, or sensitive personal data in localStorage. Any JavaScript running on the page, including third-party scripts, can read it, so a cross-site scripting flaw anywhere on the page exposes everything stored there. Treat localStorage as a public notebook for harmless preferences, not a safe. For anything sensitive, rely on server-side sessions with secure, httpOnly cookies instead. Also remember that localStorage is synchronous; reading and writing very large strings can block the interface briefly, reinforcing that it is meant for small data. Expiry is not built in either: if you need values that age out, store a timestamp alongside the data, formatted consistently, and check it on read, deleting stale entries yourself.
function setWithExpiry(key, value, ttlMinutes) {
const record = {
value: value,
expiresAt: Date.now() + ttlMinutes * 60 * 1000
};
localStorage.setItem(key, JSON.stringify(record));
}
function getWithExpiry(key) {
const raw = localStorage.getItem(key);
if (!raw) return null;
const record = JSON.parse(raw);
if (Date.now() > record.expiresAt) {
localStorage.removeItem(key);
return null;
}
return record.value;
}
setWithExpiry("banner-dismissed", true, 60);
console.log(getWithExpiry("banner-dismissed"));
These two functions add a simple expiry layer. The setter wraps your value in an object with an expiresAt timestamp calculated from the current time plus the time-to-live in minutes, then stores the wrapped object as JSON. The getter parses the record, compares the current time to the expiry, and deletes and ignores the entry if it has expired. A “banner dismissed” flag that returns after an hour is a typical use. The pattern shows a broader lesson: localStorage gives you raw string storage only, and every richer behaviour, from objects to expiry, is a thin layer you build on top with JSON and timestamps.
Conclusion
localStorage rewards a few careful habits. Save strings with setItem, read with getItem and always handle the null case, convert structured data with JSON, and delete precisely with removeItem instead of wiping everything. Use a safe helper for JSON reads, respect the size limit, and never place secrets or sensitive data in it. With those rules in place, remembering themes, drafts, carts, and small pieces of state becomes a few lines of dependable code that make your site feel considerate and complete.



