JavaScript · The language round
What is the difference between localStorage, sessionStorage and cookies?
Short answer
localStorage persists until cleared, sessionStorage lasts for the tab session, and cookies are small key-value pairs sent with HTTP requests. Cookies support HttpOnly, Secure and SameSite.
The right choice depends on lifetime, size and whether the server needs the value. Storage APIs are convenient but accessible to JavaScript; cookies can be protected from JavaScript and scoped to requests.
localStorage: about 5 MB per origin, persists across tabs and restartssessionStorage: about 5 MB per origin, scoped to one tab and cleared when it closes- Cookies: about 4 KB each, sent automatically with matching requests
HttpOnlycookies cannot be read by JavaScriptSecurecookies are only sent over HTTPSSameSitecontrols cross-site sending and helps with CSRF
localStorage.setItem("theme", "dark");
console.log(localStorage.getItem("theme")); // "dark"
sessionStorage.setItem("draft", "hello");
console.log(sessionStorage.getItem("draft")); // "hello"Security trade-offs
Anything in localStorage or sessionStorage is readable by any script on the page, so an XSS bug can steal it. Auth tokens are safer in HttpOnly, Secure, SameSite cookies because JavaScript cannot read them, but cookies introduce CSRF considerations that must be handled separately.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Where should auth tokens be stored?
- 2What does `HttpOnly` protect against?
- 3How does `SameSite` help with CSRF?
- 4Why is `localStorage` synchronous?
Say it in the interview
localStorage persists until cleared and is shared across tabs. sessionStorage lasts for one tab session. Both are accessible to JavaScript and hold around five megabytes. Cookies are small, sent with matching HTTP requests, and can be HttpOnly, Secure and SameSite. I use storage for non-sensitive UI state and prefer HttpOnly cookies for auth tokens, while handling CSRF separately.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.