Junior — Middle
What are the main differences between LocalStorage, SessionStorage, and Cookies in data storage in browsers?
sobes.tech AI
Answer from AI
LocalStorage, SessionStorage, and Cookies are three methods of storing data in the browser, but they differ in size, lifespan, and scope:
-
LocalStorage:
- Stores data indefinitely until manually cleared by the user.
- Data is accessible across all tabs and windows of the same domain.
- Usually around 5-10 MB in size.
- Not sent to the server with each request.
-
SessionStorage:
- Data persists only within a single session (while the tab is open).
- Data is not accessible in other tabs or windows.
- Similar size to LocalStorage.
- Not sent to the server.
-
Cookies:
- Limited in size (about 4 KB).
- Can have an expiration date after which they are deleted.
- Sent to the server with each HTTP request to the relevant domain.
- Used for authentication, session tracking, etc.
Example of using LocalStorage:
// Save data
localStorage.setItem('username', 'user123');
// Retrieve data
const user = localStorage.getItem('username');