Was this asked in an interview?
Web Fundamentals interview practice: Compare the three client storage mechanisms and when to use each.
Web Fundamentals interview practice: Compare the three client storage mechanisms and when to use each.
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Capacity | ~5-10 MB | ~5 MB | ~4 KB |
| Lifetime | Until cleared | Until tab closes | Expires/Max-Age |
| Sent to server | No | No | Yes, on every request |
| Scope | Origin | Origin + tab | Domain/path |
| Access | JS only | JS only | JS (unless HttpOnly) + server |
Use cases:
HttpOnly, Secure, SameSite to mitigate XSS/CSRF). Avoid storing sensitive tokens in localStorage (readable by any JS → XSS risk).localStorage.setItem("theme", "dark");
sessionStorage.setItem("step", "2");
document.cookie = "id=abc; Max-Age=3600; Secure; SameSite=Lax";