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:
Method | Description |
---|---|
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 |
length | Returns the number of stored items |
🔍 localStorage vs sessionStorage
Feature | localStorage | sessionStorage |
---|---|---|
Persistence | Stays until cleared manually | Removed when tab/window is closed |
Scope | Shared across tabs and windows | Only available in same tab |
Use Cases | Settings, themes, saved users | Temporary quiz or form state |
🧠 Key Takeaway
localStorage
: persistent client-side storagesessionStorage
: 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
Advertisement Slot 1
Advertisement Slot 2