Local Storage and Session Storage
Objectives
By the end of this chapter, you should be able to:
- Save, read, and remove data with
localStorage - Explain how
sessionStoragediffers fromlocalStorage - Store an object or array by converting it to and from JSON
๐ก Why this matters: A page normally forgets everything the moment it’s closed or reloaded.
localStorageandsessionStorageare the simplest way to make something stick around, no server required.
What You’re Building
A tiny notes page: one textarea, a “Save” button, and a “Clear” button. By the end of this lesson, it remembers your note after a reload, keeps a live draft while you type, and can wipe everything clean.
notes-app/
โโโ index.html
โโโ script.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My Notes</title>
</head>
<body>
<h1>My Notes</h1>
<textarea id="noteInput" rows="6" cols="40"></textarea>
<br>
<button id="saveBtn">Save</button>
<button id="clearBtn">Clear</button>
<p id="status"></p>
<script src="script.js"></script>
</body>
</html>
Everything from here on goes in script.js.
Step 1: Save a Note
localStorage.setItem(key, value) saves a value that survives even after the tab is closed, the browser is quit, or the computer restarts. .getItem(key) reads it back.
const noteInput = document.getElementById("noteInput");
const saveBtn = document.getElementById("saveBtn");
const status = document.getElementById("status");
saveBtn.addEventListener("click", () => {
localStorage.setItem("savedNote", noteInput.value);
status.textContent = "Note saved!";
});
Type something and click “Save”. localStorage.getItem("savedNote") now holds it, permanently, until something removes it.
Step 2: Load It Back on the Next Visit
A saved note is only useful if the page actually shows it again. Run this once, when the page first loads.
const savedNote = localStorage.getItem("savedNote");
if (savedNote) {
noteInput.value = savedNote;
status.textContent = "Loaded your saved note";
} else {
status.textContent = "No saved note yet";
}
.getItem() returns null for a key that was never set, not undefined, the if (savedNote) check handles both an empty string and null the same way: nothing to load.
Step 3: Autosave a Draft with sessionStorage
sessionStorage has the exact same methods as localStorage, .setItem(), .getItem(), .removeItem(), but what it stores only lasts for the current tab. Closing the tab clears it, unlike localStorage. That makes it a better fit for a draft that’s still in progress, not something the user explicitly chose to save.
noteInput.addEventListener("input", () => {
sessionStorage.setItem("draftNote", noteInput.value);
});
Now every keystroke updates sessionStorage, independent of the “Save” button. If the page reloaded right now (without clicking “Save” first), sessionStorage.getItem("draftNote") would still have the latest typed text, this lesson’s page doesn’t wire that reload behavior up, but the data is there, ready for it.
Step 4: Clear Everything
const clearBtn = document.getElementById("clearBtn");
clearBtn.addEventListener("click", () => {
localStorage.removeItem("savedNote");
sessionStorage.removeItem("draftNote");
noteInput.value = "";
status.textContent = "Cleared";
});
.removeItem(key) deletes just that one entry, localStorage.clear() would wipe every key this page has ever saved, useful here too, but .removeItem() is more precise when a page has saved more than one thing and you only want to clear its own keys.
Storing More Than a String: JSON
The note above is a plain string, localStorage only ever stores strings, but JSON.stringify() and JSON.parse() (Course 1) make it just as easy to save an object or array.
const preferences = { fontSize: 16, theme: "dark" };
localStorage.setItem("preferences", JSON.stringify(preferences));
const saved = JSON.parse(localStorage.getItem("preferences"));
console.log(saved);
// { fontSize: 16, theme: "dark" }
If this notes page later grew a font-size or color setting, this is exactly the pattern it would use, JSON.stringify() going in, JSON.parse() coming back out.
The Complete script.js
const noteInput = document.getElementById("noteInput");
const saveBtn = document.getElementById("saveBtn");
const clearBtn = document.getElementById("clearBtn");
const status = document.getElementById("status");
const savedNote = localStorage.getItem("savedNote");
if (savedNote) {
noteInput.value = savedNote;
status.textContent = "Loaded your saved note";
} else {
status.textContent = "No saved note yet";
}
saveBtn.addEventListener("click", () => {
localStorage.setItem("savedNote", noteInput.value);
status.textContent = "Note saved!";
});
noteInput.addEventListener("input", () => {
sessionStorage.setItem("draftNote", noteInput.value);
});
clearBtn.addEventListener("click", () => {
localStorage.removeItem("savedNote");
sessionStorage.removeItem("draftNote");
noteInput.value = "";
status.textContent = "Cleared";
});
Open index.html in a browser, type a note, click “Save”, then reload the page, the note is still there.
Try It
Extend the notes page from this lesson:
- Add a character count: every time
noteInputfires aninputevent, update#statusto show how many characters are currently in the textarea. - Change the “Clear” button so it also resets that character count back to
0. - Add a
{ savedAt: <timestamp> }object alongside the note, saved tolocalStorageas JSON under the key"noteMeta"whenever “Save” is clicked, usingDate.now()for the timestamp. - On page load, if
"noteMeta"exists, parse it and show`Last saved at ${saved.savedAt}`in#statusinstead of the plain “Loaded your saved note” message.
Recap
localStorage.setItem(key, value)and.getItem(key)save and load data that persists indefinitely, this lesson’s “Save” button and page-load check used exactly this pair.sessionStoragehas the same API but clears when the tab closes, a natural fit for an in-progress draft that autosaves as the user types..removeItem(key)clears one saved value, this lesson’s “Clear” button used it on both storages at once.- Store objects or arrays by converting with
JSON.stringify()on the way in andJSON.parse()on the way out.
Next lesson: cookies, an older way of storing small amounts of data, still used for things localStorage isn’t suited for.