Local Storage and Session Storage
Local Storage & Session Storage
Persistent Data in the Browser
By AI Learning Assistant · JavaScript · Web Storage · Client-Side Persistence
🤖 AI-POWERED LESSON
This article is paired with a live AI session. Every code block includes detailed line-by-line comments explaining WHY each line exists and HOW it works in real applications.
Have you ever refreshed a webpage and watched your unsaved work disappear? Frustrating, right? That's because most data lives only in memory. When the page reloads, memory is wiped clean. But what if you could save data that survives page refreshes, browser restarts, and even days later? That's what Web Storage gives you.
Think of localStorage as a small filing cabinet inside the user's browser. Your JavaScript can put data in, take data out, and clear it away. The data stays there until you explicitly remove it — even if the user closes the browser and comes back next week. SessionStorage is like a sticky note on your desk: it's there while you're working, but when you close the office door (the browser tab), the note disappears.
We will cover localStorage vs sessionStorage vs cookies, saving and retrieving data, storing objects as JSON strings, automatic page load restoration, and real-world use cases from theme preferences to shopping carts.
localStorage vs sessionStorage
PERSISTENCE · SCOPE · LIFECYCLE
Both localStorage and sessionStorage are part of the Web Storage API. They store key-value pairs where both keys and values are strings. The key difference is lifetime and scope.
📜 CODE BLOCK 1: localStorage and sessionStorage Basic Operations (with line-by-line comments)
// ============================================ // LOCALSTORAGE — persists until manually deleted // ============================================ // WHY: To save user preferences across browser sessions // HOW: setItem(key, value) stores a string value under a key localStorage.setItem("theme", "dark"); // After this line, "dark" is saved in the browser's storage // Close the browser, restart your computer — it's still there // WHY: To retrieve saved data when page loads // HOW: getItem(key) returns the stored string, or null if not found const savedTheme = localStorage.getItem("theme"); // savedTheme now equals "dark" (the string we stored earlier) // WHY: To delete a specific item when user changes preference // HOW: removeItem(key) deletes only that key-value pair localStorage.removeItem("theme"); // WHY: To clear ALL data for this origin (use with caution!) // HOW: clear() empties the entire localStorage for this domain // localStorage.clear(); // Uncomment to wipe everything // ============================================ // SESSIONSTORAGE — cleared when tab/window closes // ============================================ // WHY: To store temporary data that shouldn't outlive the tab // Example: multi-step form progress, checkout state sessionStorage.setItem("formStep", "2"); // WHY: To retrieve the temporary data const currentStep = sessionStorage.getItem("formStep"); // currentStep equals "2" — but only if the tab hasn't been closed // WHY: Different tabs have DIFFERENT sessionStorage // Open two tabs of the same website — they don't share sessionStorage! // This is perfect for keeping separate states per tab
Build a Notes Saver
PERSISTENT NOTES · AUTO-LOAD · CLEAR
📓 My Dev Notes — Try It Yourself
✨ No saved notes found. Write something and save!
📜 CODE BLOCK 2: Complete Notes Saver Application (with line-by-line comments)
// ============================================ // COMPLETE NOTES SAVER WITH LOCALSTORAGE // ============================================ // WHY: This function runs when the page finishes loading // HOW: window.onload event fires after all DOM elements exist window.onload = function() { // WHY: Get the saved notes from localStorage (if any) // HOW: getItem returns null if the key doesn't exist const saved = localStorage.getItem("devNotes"); // WHY: Check if we actually have saved content // HOW: if saved is not null, populate the textarea if (saved) { // WHY: document.getElementById finds the textarea element // HOW: .value property reads/writes the text inside document.getElementById("notes").value = saved; } } // WHY: This function saves the current notes to localStorage // HOW: Called when the Save button is clicked function saveNotes() { // WHY: Read what the user typed in the textarea const notes = document.getElementById("notes").value; // WHY: Store the notes in localStorage with key "devNotes" // HOW: setItem takes (key, value) — both must be strings localStorage.setItem("devNotes", notes); // WHY: Show confirmation to the user // HOW: Update the status paragraph's text and color const status = document.getElementById("status"); status.textContent = "Notes saved!"; status.style.color = "green"; } // WHY: This function removes notes from both UI and storage // HOW: removeItem deletes the key, then clear the textarea function clearNotes() { // WHY: Delete the item from localStorage permanently localStorage.removeItem("devNotes"); // WHY: Also clear the textarea so user sees empty field document.getElementById("notes").value = ""; // WHY: Update status to inform user const status = document.getElementById("status"); status.textContent = "Notes cleared."; status.style.color = "red"; }
✅ WHAT'S HAPPENING IN THIS CODE
localStorage.setItem("key", "value") saves data. localStorage.getItem("key") retrieves it (returns null if not found). localStorage.removeItem("key") deletes it. The window.onload event ensures we load saved data after the page elements exist. This is the exact pattern used by millions of production apps for saving drafts, preferences, and settings.
Storing Objects in localStorage
JSON.STRINGIFY · JSON.PARSE · THE MOST COMMON MISTAKE
Real applications store more than simple strings. You'll want to save user preferences, shopping cart items, or form data as objects. localStorage only stores strings — so you must convert objects to JSON strings before saving, and parse them back when retrieving.
📜 CODE BLOCK 3: Saving and Retrieving Objects (with comments)
// ============================================ // STORING OBJECTS — THE RIGHT WAY // ============================================ // WHY: Create a complex object with multiple properties // This could be user preferences, cart items, or app state const userPreferences = { theme: "dark", fontSize: 16, notifications: true, language: "en-US" }; // WHY: localStorage only accepts strings, not objects // If you try localStorage.setItem("prefs", userPreferences), // it will store "[object Object]" — USELESS! // HOW: JSON.stringify converts the object into a JSON string // The result looks like: '{"theme":"dark","fontSize":16,...}' const preferencesString = JSON.stringify(userPreferences); // NOW we can save it to localStorage localStorage.setItem("preferences", preferencesString); // ============================================ // RETRIEVING OBJECTS — THE RIGHT WAY // ============================================ // WHY: Get the JSON string back from storage const savedString = localStorage.getItem("preferences"); // HOW: JSON.parse converts the JSON string back into a real object if (savedString) { const restoredPrefs = JSON.parse(savedString); // restoredPrefs.theme === "dark" // restoredPrefs.fontSize === 16 // Now you can use the object properties in your app! console.log(`Theme is ${restoredPrefs.theme}`); } // ============================================ // COMMON MISTAKE — WHAT NOT TO DO // ============================================ // ❌ WRONG: Trying to store object directly localStorage.setItem("bad", userPreferences); // This stores "[object Object]" — completely broken! // ❌ WRONG: Forgetting to parse when retrieving const badData = localStorage.getItem("preferences"); // badData.theme will be undefined because badData is a STRING, not an object! // You must ALWAYS parse after getting, and stringify before setting.
Quick Comparison
| FEATURE | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Capacity | 5-10MB | 5-10MB | 4KB per domain |
| Lifetime | Permanent (until deleted) | Until tab closes | Session or custom date |
| Sent to server | No | No | Yes (every request) |
| Accessible from JS | Yes | Yes | Yes (unless HttpOnly) |
| Best for | Preferences, offline data | Multi-step forms, temp state | Auth tokens, tracking |
🤖 HOW AI ACCELERATES THIS TOPIC
Ask AI: "Design a localStorage schema for a todo app with tasks, due dates, and completion status — show me the JSON structure and the code to save/load it."
Ask: "Why is my stored object showing as [object Object] instead of my data?" The AI will explain JSON.stringify and JSON.parse with examples.
Ask: "Convert my cookie-based session management to use localStorage — what are the security implications?" Get a thorough security analysis for production.
AI-Assisted JavaScript Learning · Web Storage API · Build Persistent User Experiences
Complete this lesson
Mark as complete to track your progress