Unit 3: Objects, DOM & Browser Web APIsLesson #10 / 10

Lesson 10: LocalStorage, SessionStorage & Client Persistence

Er. Manoj Kumar — AuthorEr. Manoj KumarLast Updated: 26 Aug, 2026

1. Browser Web Storage APIs

Web Storage allows client applications to store key-value string data directly in the browser:

  • localStorage: Persists permanently across sessions until cleared (localStorage.setItem('key', val)).
  • sessionStorage: Persists only for the duration of the active browser tab.
  • Saving Objects: Must serialize with JSON.stringify() before storing and JSON.parse() upon retrieval.
  • HTML5 Web Code (index.html)
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>LocalStorage Persistence</title>
    </head>
    <body style="background:#17181c; color:#fff; font-family:Arial; padding:30px;">
    <h2>Persistent Preference Storage</h2>
    <button id="save-theme-btn" style="padding:10px 18px; background:#04AA6D; color:#fff; border:none; border-radius:6px; font-weight:bold; cursor:pointer;">
    Toggle & Save Dark Theme
    </button>
    <p id="storage-status" style="margin-top:14px; font-mono text-xs;"></p>
    <script>
    const btn = document.getElementById("save-theme-btn");
    const status = document.getElementById("storage-status");
    // Check existing stored setting
    const savedTheme = localStorage.getItem("app_theme") || "dark";
    status.textContent = "Current Saved Theme: " + savedTheme;
    btn.addEventListener("click", () => {
    const current = localStorage.getItem("app_theme") === "light" ? "dark" : "light";
    localStorage.setItem("app_theme", current);
    status.textContent = "Current Saved Theme: " + current + " (Saved to LocalStorage!)";
    });
    </script>
    </body>
    </html>

    Interactive Knowledge Check

    Test your understanding of Lesson #10 concepts

    How long does data stored in window.localStorage persist?