OnlineCBT Logo OnlineCBT
JavaScript Tutorial
JAVASCRIPT · LESSON 33

Browser Web Storage: localStorage and sessionStorage

By Ratan Updated: 16 Oct 2026

Store key-value data persistently in the user's browser with JSON serialization.

Level: Beginner to Advanced
Duration: ~60 Mins Deep-Dive

Persist small browser preferences deliberately

localStorage and sessionStorage store string key/value pairs for a site origin. localStorage commonly persists beyond a tab session; sessionStorage is scoped to an origin within a top-level browsing context and normally lasts for that tab's session. Neither is a substitute for a server account database.

const key = 'onlinecbt.practice.theme.v1';
function saveTheme(theme) {
  if (!['light', 'dark', 'system'].includes(theme)) return false;
  try {
    localStorage.setItem(key, theme);
    return true;
  } catch {
    return false;
  }
}
function loadTheme() {
  try {
    const value = localStorage.getItem(key);
    return ['light', 'dark', 'system'].includes(value) ? value : 'system';
  } catch {
    return 'system';
  }
}
console.log(saveTheme('dark'));
console.log(loadTheme());

In an ordinary permitted context, saveTheme returns true and loadTheme returns dark. Browser settings, private modes, policies or quota limits can make storage unavailable; the example retains a safe fallback.

Strings and structured data

setItem converts values to strings. To store a small object, serialize it with JSON.stringify and parse it with error handling. Validate the parsed shape and version before using it. A previous application version or manual browser edit can leave unexpected data.

Security and privacy

Scripts running on the origin can access Web Storage. Do not store passwords, private API keys or sensitive account data there. XSS can expose browser-readable tokens; choose authentication storage according to the application's security design rather than treating localStorage as a secure vault.

Scope and cleanup

Scheme, host and port are part of origin. An HTTP development site and its HTTPS production site do not share storage automatically. removeItem deletes one key; clear removes all keys in that storage area and may disrupt unrelated features. Use namespaced keys and targeted removal.

Practice

  1. Save a harmless preferred language and restore it on reload.
  2. Compare localStorage and sessionStorage across reloads and separate tabs.
  3. Simulate malformed JSON and keep the UI usable.
  4. Explain why changing a local role string must never grant server admin access.

📝 Live Lesson Practice

HTML/CSS JavaScript Python C++ C PHP
⌨️ Practice Inputs (लाइव इनपुट भरें) (खाली होने पर RED, भरने पर GREEN underline)
💻 Code Editor (Monaco VS Code Engine)
👀 Live Preview
Address Contact

+91 7877547686

E-mail

onlinecbtportal@gmail.com

Helpline Number

+91 7877547686


Click To Download
Get it on Google Play

ऐप डाउनलोड करने
के लिए Google Play पर
उपलब्ध है

WhatsApp Chat