The Storage API has just a handful of methods.
| Method | Does |
|---|---|
setItem(key, value) | saves (or overwrites) a value |
getItem(key) | reads a value, or null if missing |
removeItem(key) | deletes one key |
clear() | deletes everything for this site |
key(index) | name of the key at a position |
length | how many items are stored |
localStorage.setItem("name", "Maya");
localStorage.setItem("city", "Pune");
console.log(localStorage.getItem("name")); // → Maya
console.log(localStorage.getItem("missing")); // → null
console.log(localStorage.length); // → 2
localStorage.removeItem("city");
console.log(localStorage.getItem("city")); // → null
localStorage.clear();
console.log(localStorage.length); // → 0
Handle a missing value
getItem returns null when the key does not exist. Use ?? for a default.
const theme = localStorage.getItem("theme") ?? "light";
console.log(theme); // → light
Example: a theme that remembers
<style>
body.dark { background: #1c1b1f; color: #eee; }
</style>
<button id="toggle">Toggle theme</button>
<script>
const body = document.body;
// apply the saved choice when the page loads
if (localStorage.getItem("theme") === "dark") {
body.classList.add("dark");
}
document.querySelector("#toggle").addEventListener("click", () => {
const isDark = body.classList.toggle("dark");
localStorage.setItem("theme", isDark ? "dark" : "light");
});
</script>
On a real page, reload after toggling and the theme stays. (Here, the editor keeps storage for one run only.)
Other ways to read keys
localStorage.setItem("a", "1");
localStorage.setItem("b", "2");
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
console.log(key, localStorage.getItem(key));
}
You can also use property syntax (localStorage.theme = "dark"), but the methods are safer: a key like length would clash with the real property.
Namespacing keys
Many apps share one origin, such as several pages on the same site. Use a prefix to avoid clashes:
localStorage.setItem("notes-app:draft", text);
Errors can happen
Storage can be unavailable (private mode in some browsers, blocked by settings) or full. Wrap writes you care about in try...catch, as shown in Storage Limits.
Reading often
getItem is quick, but do not read and write on every keystroke of a fast event. Save when the user pauses (see Debouncing) or leaves the field.