Originally published on CodingCush.
JavaScript localStorage is a small storage box built into the browser that lets a website save text and read it back later, even after the tab is closed and the browser is restarted. It stores data as key and value pairs, holds about 5 MB per website, and never sends anything to the server. If you have ever picked dark mode on a website and found it still dark the next day, localStorage probably did that. Below: how it compares with its rivals, the four methods that do the work, and a theme toggle that remembers your choice.
localStorage vs sessionStorage vs Cookies: The Comparison First
Beginners mix these three up because they all "remember things". This table settles it.
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Lifetime | No expiry. Stays until deleted. | Gone when the tab closes. | You set the expiry, or it ends with the session. |
| Size | About 5 MB per website. | About 5 MB per website. | About 4 KB per cookie. |
| Sent to the server? | No. It stays in the browser. | No. It stays in the browser. | Yes, with every request. |
| Scope | Every tab of the same website shares it. | One tab only. | Sent with requests to that domain. |
| Best for | Settings, themes, a saved name. | Temporary data for one tab. | Logins and server sessions. |
Two rows matter most. First, lifetime: localStorage has no expiry date while sessionStorage dies with the tab, so a theme choice belongs in localStorage and a half filled form in one tab belongs in sessionStorage. Second, the server row: cookies travel to the server with every request, so they are the right tool when the server needs the data. For the full story on the server side, read how PHP sessions and cookies differ.
What localStorage Actually Is
localStorage is a property of the browser window that gives you a Storage object for the current website. In friendly terms, every website gets its own little notebook inside your browser, and JavaScript can write notes in it and read them back on later visits. The notebook belongs to one origin, one combination of protocol, domain and port, so a page on https and the same page on http get different notebooks. The MDN reference for Window.localStorage states it plainly: the stored data is saved across browser sessions, and unlike sessionStorage it has no expiration time.
One more thing worth knowing: localStorage is synchronous, which means the browser stops and waits while it reads or writes. For the small strings beginners store, that pause is too tiny to notice. If the word synchronous sounds new, read our explanation of the JavaScript event loop to see how the browser handles one task at a time.
The Four Methods You Need
Almost everything you will ever do with localStorage uses four methods.
setItem saves a value under a key. getItem reads it back. That pair covers most real uses:
localStorage.setItem("username", "Lavkush");
const savedName = localStorage.getItem("username");
console.log(savedName);
Output:
Lavkush
The other two methods clean up. removeItem deletes one key, and clear wipes the whole notebook for that website:
localStorage.removeItem("username");
console.log(localStorage.getItem("username"));
localStorage.setItem("theme", "dark");
localStorage.clear();
console.log(localStorage.getItem("theme"));
console.log(localStorage.length);
Output:
null
null
0
Notice the surprise in that output. Reading a key that does not exist returns null, not an empty string and not an error. Expect null and handle it, usually with a fallback value, as the theme example later in this article shows.
The MDN page for Window: localStorage property, the official reference for the storage methods used in this guide.
Why Your Saved Data Disappears
Read this section when your code looks right but the data is gone on the next visit. Four causes cover almost every case.
You tested from a file on your computer. Opening an HTML file straight from your disk gives it a file address, and the rules for localStorage on file addresses are undefined. Serve your page from a local server instead.
You are in a private or incognito window. localStorage works there, but the data is cleared when the last private tab closes. That is by design, so test in a normal window.
The browser is blocking storage. If the user blocks cookies, most browsers treat that as an instruction to block persistent storage too, and localStorage calls can throw a SecurityError. Wrap your first setItem call in a try catch block so the page keeps working.
You stored it under http and looked for it under https. The notebook belongs to one protocol, domain and port. Switching between http and https, or between localhost and 127.0.0.1, means switching notebooks. Pick one address and stick to it.
Saving an Object? Turn It into a String First
localStorage stores strings only. That rule sounds harmless until you save an object and get a nasty surprise:
const user = { name: "Lavkush", level: "beginner", theme: "dark" };
localStorage.setItem("user", user);
console.log(localStorage.getItem("user"));
Output:
[object Object]
JavaScript quietly converted your object into the string "[object Object]", and your data is gone. The fix is a two step habit: JSON.stringify turns the object into a string before saving, and JSON.parse turns it back into an object when you read it:
localStorage.setItem("user", JSON.stringify(user));
const savedUser = JSON.parse(localStorage.getItem("user"));
console.log(savedUser.name);
console.log(savedUser.theme);
Output:
Lavkush
dark
Once you have the object back, you can pull single values out of it with JavaScript destructuring, a tidy way to grab name, theme and level in one line. Remember: stringify on the way in, parse on the way out, every time.
Careful: Numbers Come Back as Strings
The same string only rule bites with numbers. Save the number 3, read it back, and you get the string "3". Add 1 and JavaScript glues the characters together instead of doing maths:
localStorage.setItem("visits", 3);
const visits = localStorage.getItem("visits");
console.log(typeof visits);
console.log(visits + 1);
console.log(Number(visits) + 1);
Output:
string
31
4
That second line is the classic beginner bug: "3" plus 1 becomes "31". The fix is one word, Number(), wrapped around the value before you do maths with it.
A Theme Toggle That Remembers Your Choice
Now the running example: one button that switches a page between light and dark mode and remembers the choice:
<button id="themeButton">Switch to dark mode</button>
The JavaScript:
const button = document.getElementById("themeButton");
function applyTheme(theme) {
if (theme === "dark") {
document.body.classList.add("dark-mode");
button.textContent = "Switch to light mode";
} else {
document.body.classList.remove("dark-mode");
button.textContent = "Switch to dark mode";
}
}
const savedTheme = localStorage.getItem("theme") || "light";
applyTheme(savedTheme);
button.addEventListener("click", function () {
const newTheme = localStorage.getItem("theme") === "dark" ? "light" : "dark";
localStorage.setItem("theme", newTheme);
applyTheme(newTheme);
});
Three ideas make this work. First, the page load line reads the saved theme and falls back to "light" when getItem returns null on the very first visit. Second, the click handler flips the value and saves it before updating the screen, so the stored choice and the visible page can never disagree. Third, applyTheme does the visible work in one place. Read a saved value, fall back to a default, save on change: that is the shape of most localStorage code.
When localStorage Is the Wrong Tool
A good developer knows when not to use a tool. Do not store passwords, tokens or anything secret in localStorage, because any JavaScript running on your page can read it. Do not store data the server needs, because localStorage never leaves the browser; cookies and server sessions exist for that job. Do not store large data such as image files or long lists; about 5 MB fills up fast, and for bigger jobs the browser offers IndexedDB instead. The Web Storage API overview on MDN lists these same boundaries and points to the bigger storage tools when you outgrow key and value pairs.
Questions Beginners Keep Asking
Is localStorage safe for storing passwords?
No. Any script on the page can read localStorage, so a password or login token stored there is exposed. Keep secrets on the server and use secure cookies for logins.
How much data can localStorage hold?
About 5 MB per website in most browsers. Saving more throws an error, so keep what you store small.
Does localStorage work in private or incognito mode?
Yes, but the data is cleared when the last private tab closes, so never rely on it for anything important there.
Can another website read my localStorage data?
No. Storage is separated by origin, so only pages from the same origin can read it.
Does localStorage need an internet connection?
No. The data lives in the browser on the device, so it works fully offline.
Quick Quiz: Did It Stick?
Three fast questions. First, which method reads a value back? Answer: getItem, with the key as its argument. Second, what do you get when you read a key that was never saved? Answer: null, so always plan a fallback value. Third, why does saving an object directly print "[object Object]"? Answer: localStorage stores strings only, so stringify first and parse on the way back. Three out of three means you are ready to build the theme toggle yourself.

Top comments (0)