HTML Web Storage

Subject: html

💾 HTML Web Storage

HTML Web Storage provides a way to store key/value data in the browser, without involving the server. It's faster and more secure than cookies.

HTML5 offers two types:

  • localStorage — persists even after the browser is closed.
  • sessionStorage — lasts only for the current browser session.

✅ Why Use Web Storage?

  • Data is stored locally and not sent with every HTTP request
  • Holds more data than cookies (typically 5–10MB)
  • Useful for:
    • Saving user preferences
    • Temporary form data
    • Storing login/session status

📌 1. localStorage Example


📌 2. sessionStorage Example


🧠 Web Storage Methods

Both localStorage and sessionStorage use the same methods:

MethodDescription
setItem(key, value)Adds a key/value pair
getItem(key)Retrieves value by key
removeItem(key)Removes the specified key/value pair
clear()Clears all key/value pairs
lengthReturns the number of stored items

🔍 localStorage vs sessionStorage

FeaturelocalStoragesessionStorage
PersistenceStays until cleared manuallyRemoved when tab/window is closed
ScopeShared across tabs and windowsOnly available in same tab
Use CasesSettings, themes, saved usersTemporary quiz or form state

🧠 Key Takeaway

  • localStorage: persistent client-side storage
  • sessionStorage: temporary session-only storage
  • Use Web Storage to improve performance and reduce server dependence
  • All data is stored as strings — use JSON.stringify()/JSON.parse() for objects