-
Hajipur, Bihar, 844101
HTML Web Storage provides a way to store data on the client’s browser. It is more secure and faster than cookies and offers two main types:
Local Storage — stores data with no expiration time. Data persists even after the browser is closed and reopened.
Session Storage — stores data for the duration of the page session (until the tab or browser is closed).
Both are accessed via the window.localStorage
and window.sessionStorage
objects in JavaScript.
Feature | Local Storage | Session Storage |
---|---|---|
Lifespan | Persistent (until cleared) | Until tab/browser is closed |
Storage Limit | ~5MB (varies by browser) | ~5MB (varies by browser) |
Shared Across Tabs | Yes | No (per tab session) |
Operation | Syntax | Description |
---|---|---|
Set Item | localStorage.setItem('key', 'value') |
Stores value by key |
Get Item | localStorage.getItem('key') |
Retrieves value by key |
Remove Item | localStorage.removeItem('key') |
Deletes item by key |
Clear Storage | localStorage.clear() |
Clears all stored data |
// Store data
localStorage.setItem('username', 'Bikki');
// Retrieve data
const user = localStorage.getItem('username');
console.log(user); // Output: Bikki
// Remove data
localStorage.removeItem('username');
// Clear all
localStorage.clear();
// Store data
sessionStorage.setItem('theme', 'dark');
// Retrieve data
const theme = sessionStorage.getItem('theme');
console.log(theme); // Output: dark
// Remove data
sessionStorage.removeItem('theme');
// Clear all
sessionStorage.clear();
Q1. Store a user's name in localStorage and display it on page load.
Q2. Save a user's theme preference (light/dark) in sessionStorage.
Q3. Remove a specific item from localStorage on button click.
Q4. Clear all sessionStorage when user logs out.
Q5. Use localStorage to keep track of the number of visits to a page.
Q6. Store form data temporarily using sessionStorage.
Q7. Update an existing value in localStorage.
Q8. Check if a key exists in localStorage before using it.
Q9. Use localStorage to save a user's language preference.
Q10. Implement a toggle that switches theme and stores the current selection using Web Storage.
Q1: Which Web Storage persists data even after closing the browser?
Q2: Which method is used to store data in Web Storage?
Q3: How do you retrieve data from Web Storage?
Q4: What is the lifespan of sessionStorage data?
Q5: Which method removes one key from Web Storage?
Q6: Which Web Storage object is shared across all tabs in the same origin?
Q7: How can you clear all data from localStorage?
Q8: Can Web Storage store complex objects like arrays?
Q9: What happens if you store an object directly in localStorage?
Q10: Which method can be used to convert an object to a JSON string?