Web Storage: localStorage & sessionStorage
Save data right in the browser so it survives a refresh — the simple trick behind remembered to-do lists, carts and dark-mode settings.
What you will learn
- Save and read values with localStorage
- Store objects by combining it with JSON
- Tell localStorage and sessionStorage apart
A tiny notebook inside the browser
Normally, every variable in your JavaScript vanishes the moment the page reloads. Web Storage gives you a small notebook inside the browser where you can write values that survive a refresh — and even survive closing the tab. It is how a to-do app remembers your tasks and a site remembers you chose dark mode.
The main tool is localStorage. It has just two everyday commands: setItem(key, value) to save, and getItem(key) to read back. You give each value a key (a name) so you can find it again — exactly like a labelled box.
<input id="name" placeholder="Type your name">
<button id="save">Save</button>
<p id="greet"></p>
<script>
// On load: read any previously saved name and greet
const saved = localStorage.getItem("username");
if (saved) document.getElementById("greet").textContent = "Welcome back, " + saved + "!";
document.getElementById("save").addEventListener("click", function () {
const value = document.getElementById("name").value;
localStorage.setItem("username", value); // save it
document.getElementById("greet").textContent = "Saved! Now refresh the page.";
});
</script>Walk through what happens:
- When the page loads,
localStorage.getItem("username")looks for a value saved under the key "username". - The very first time, nothing is saved yet, so it returns
nulland we skip the greeting. - You type a name and click Save:
localStorage.setItem("username", value)writes it into the browser’s notebook. - Now refresh the page. This time
getItem("username")finds your saved name and greets you with it. - The value stays even if you close the tab and come back tomorrow — that is the whole point of
localStorage.
Note: Output: First visit: (no greeting) → type "Asha", click Save → "Saved! Now refresh the page." After refresh: Welcome back, Asha!
Storage only holds text — so use JSON for objects
There is one rule to remember: Web Storage can only hold strings (plain text). If you try to save an object or array directly, you get back the useless text "[object Object]". The fix is the JSON pair you already know: JSON.stringify to save, JSON.parse to read back.
<script>
const cart = { items: ["Book", "Pen"], total: 350 };
// Save: turn the object into text first
localStorage.setItem("cart", JSON.stringify(cart));
// Read: turn the text back into a real object
const back = JSON.parse(localStorage.getItem("cart"));
document.write("Items: " + back.items.join(", ") + "<br>");
document.write("Total: " + back.total);
</script>JSON.stringify(cart) flattens the object into the text {"items":["Book","Pen"],"total":350}, which Web Storage is happy to hold. To use it again, JSON.parse(...) rebuilds a real object from that text, so back.items and back.total work just like normal object properties.
Note: Output: Items: Book, Pen Total: 350
Watch out: Save the string, not the raw object. localStorage.setItem("cart", cart) (no stringify) would store the literal text "[object Object]" and lose your data. Always JSON.stringify on the way in and JSON.parse on the way out.
localStorage vs sessionStorage
There are two versions, used in exactly the same way (same setItem/getItem). The only difference is how long the data lasts.
| Store | Lasts until | Use for |
|---|---|---|
localStorage | You delete it (survives refresh AND closing the browser) | To-do lists, cart, theme choice |
sessionStorage | You close the tab | One-visit data, like a multi-step form in progress |
setItem(key, value)— save a value under a name.getItem(key)— read it back (returnsnullif not found).removeItem(key)— delete one value.clear()— wipe everything for this site.
Tip: You can SEE your stored data: open dev tools (F12) → Application tab → Local Storage. Watching values appear there as you save is a great way to understand what is happening.
Q. You want to save an array in localStorage. What must you do first?
✍️ Practice
- Save a theme choice ("dark" or "light") in
localStorageand apply it on page load. - Store an array of three favourite foods using
JSON.stringify, then read it back withJSON.parse.
🏠 Homework
- Add
localStoragesaving to your To-Do project so tasks remain after a refresh: save the list on every change, and load it when the page opens.