Describe the difference between a cookie, sessionStorage and localStorage in browsers
Answer:
Cookies, sessionStorage, and localStorage are all used for storing data in a user's browser, but they differ in scope, storage size, and how they are managed.
Cookies
- Purpose: Primarily used for storing data that needs to be sent back to the server with every HTTP request (e.g., session identifiers, user preferences).
- Storage Limit: Typically 4 KB per cookie.
- Scope:
- Accessible both by JavaScript (if not marked HttpOnly) and server.
- Can have expiration dates for persistence.
Example:
document.cookie =
'username=JohnDoe; expires=Fri, 31 Dec 2024 23:59:59 GMT; path=/';
- Cons:
- Small storage limit.
- Automatically sent with every HTTP request, increasing bandwidth usage.
localStorage
- Purpose: Stores data with no expiration, useful for persisting data across sessions.
- Storage Limit: Approximately 5–10 MB per domain.
- Scope:
- Data persists even after the browser is closed and reopened.
- Accessible only by JavaScript on the same domain.
Example:
localStorage.setItem('username', 'JohnDoe');
console.log(localStorage.getItem('username')); // "JohnDoe"
- Cons:
- Not suitable for sensitive data as it's accessible via JavaScript.
sessionStorage
- Purpose: Stores data for the duration of a page session.
- Storage Limit: Approximately 5–10 MB per domain.
- Scope:
- Data is cleared when the browser tab or window is closed.
- Accessible only by JavaScript on the same domain.
Example:
sessionStorage.setItem('username', 'JohnDoe');
console.log(sessionStorage.getItem('username')); // "JohnDoe"
- Cons:
- Data is lost when the session ends.