JavaScript Tutorial in Hindi #33 | Local Storage vs Session Storage vs Cookies (2025)
✅ 1. What is Local Storage?
- Web storage that stores data locally in the browser with no expiration.
- Data persists even after closing and reopening the browser.
- Stores data as key-value pairs (strings only).
- Size limit: about 5-10 MB depending on the browser.
✅ 2. What is Session Storage?
- Similar to Local Storage, but data is stored only for the current browser tab/session.
- Data is cleared when the tab or browser is closed.
- Also stores key-value string pairs.
- Size limit similar to Local Storage.
✅ 3. What are Cookies?
- Small pieces of data stored by the browser.
- Sent to the server with every HTTP request (unlike Local/Session Storage).
- Can have expiration dates (can be set to expire).
- Mainly used for authentication, tracking, and session management.
- Size limit: about 4 KB per cookie.
✅ 4. Key Differences
FeatureLocal StorageSession StorageCookies | |||
Lifetime | Permanent (until cleared) | Tab/session only | Can be set to expire |
Data sent to server | No | No | Yes, with every HTTP request |
Storage size | 5-10 MB | 5-10 MB | ~4 KB per cookie |
Accessibility | Same origin only | Same origin, current tab | Same origin, sent to server |
✅ 5. Practical Examples
Local Storage
js
CopyEdit
// Save data
localStorage.setItem('username', 'Mohit');
// Read data
const name = localStorage.getItem('username');
console.log(name); // Mohit
// Remove data
localStorage.removeItem('username');
// Clear all
localStorage.clear();
Session Storage
js
CopyEdit
// Save data
sessionStorage.setItem('sessionID', '123456');
// Read data
console.log(sessionStorage.getItem('sessionID'));
// Data cleared when tab is closed
Cookies
js
CopyEdit
// Set cookie (expires in 7 days)
document.cookie = "user=Mohit; max-age=" + 7*24*60*60 + "; path=/";
// Read cookies
console.log(document.cookie);
// Delete cookie (set max-age to 0)
document.cookie = "user=; max-age=0; path=/";