What is Web Storage?
Web Storage provides a way to store data locally in the browser. It's easier and more secure than cookies. There are two types:
💡 Key insight
localStorage persists data even after the browser is closed. sessionStorage only persists for the current session.
localStorage vs sessionStorage
- localStorage: Data persists until explicitly deleted
- sessionStorage: Data is cleared when the tab is closed
- Both store data as key-value pairs (strings only)
- Limit: ~5-10MB per domain
Basic Operations
// Store data
localStorage.setItem('key', 'value');
// Retrieve data
const value = localStorage.getItem('key');
// Remove data
localStorage.removeItem('key');
// Clear all data
localStorage.clear();
// Get number of stored items
const count = localStorage.length;
Storing Objects
Since localStorage only stores strings, you need to serialize objects with JSON.
// Store object
const user = { name: 'Alice', age: 25 };
localStorage.setItem('user', JSON.stringify(user));
// Retrieve object
const stored = JSON.parse(localStorage.getItem('user'));
Common Mistakes
- Storing data without JSON.stringify for objects
- Not handling missing data when retrieving
- Storing sensitive data in localStorage (not secure)
- Exceeding storage limits without error handling
Quick Quiz
1. How does localStorage differ from sessionStorage?
2. How do you store an object in localStorage?
3. Which method removes all data from localStorage?
Summary
- localStorage persists data permanently
- sessionStorage persists until tab closes
- Store strings with
setItem(), retrieve withgetItem() - Use
JSON.stringify()andJSON.parse()for objects - Remove items with
removeItem()orclear() - Check
localStorage.lengthfor count
