JavaScript · The language round

What is the difference between localStorage, sessionStorage and cookies?

MediumstoragecookiesbrowserUpdated Oct 2026
Quiz this track

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 restarts
  • sessionStorage: about 5 MB per origin, scoped to one tab and cleared when it closes
  • Cookies: about 4 KB each, sent automatically with matching requests
  • HttpOnly cookies cannot be read by JavaScript
  • Secure cookies are only sent over HTTPS
  • SameSite controls cross-site sending and helps with CSRF
js
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.

Do not store secrets or large objects in cookies. They are sent on every matching request, which adds latency and exposes them to more surfaces.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Where should auth tokens be stored?
  2. 2What does `HttpOnly` protect against?
  3. 3How does `SameSite` help with CSRF?
  4. 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.