HTML & CSS interview question · Most asked
Compare localStorage, sessionStorage and cookies.
Summary
localStorage persists per origin until cleared; sessionStorage lasts for one tab's session; both hold a few megabytes of strings, are read only by JavaScript and aren't sent to the server. Cookies are small (about 4 KB), sent with every matching HTTP request, and can be HttpOnly, Secure and SameSite.
Longer Answer
Web storage is synchronous and string-only (serialise with JSON). Never store tokens or secrets in localStorage: any XSS can read it, while HttpOnly cookies are out of JavaScript's reach. For large or structured data use IndexedDB.
Key Points
- Web storage: client only, per origin.
- sessionStorage: per tab.
- Cookies: sent with requests.
- HttpOnly cookies for session tokens.
- IndexedDB for large data.
Deep dive: HTML Tutorial: HTML Web Storage
Explanation
What interviewers look for
Security trade-off for tokens and the request overhead of cookies.
More most-asked HTML & CSS questions
- What is ARIA, and what is the first rule of ARIA?
- What is HTML5, and how is it different from HTML 4?
- What is HTML?
- What is semantic HTML, and why does it matter?
- What is the alt attribute for, and what makes good alt text?
- What input types and validation attributes did HTML5 add?
- What is the difference between script, script async and script defer?
- What does <!DOCTYPE html> do?