1. Home
  2. Interview Questions
  3. JavaScript
  4. What is the difference between localStorage, sessionStorage …

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: localStorage keeps data per origin until it is explicitly cleared. sessionStorage keeps data per origin and per tab until that tab is closed. Cookies are small strings with an optional expiry that the browser automatically sends to the server with every matching HTTP request.

Detailed explanation

All three store key-value data in the browser. They differ in four areas that interviewers usually ask about: lifetime, scope, size and whether the server sees the data.

FeaturelocalStoragesessionStorageCookies
LifetimeUntil cleared by code or the userUntil the tab or window is closed (survives reloads)Until the Expires/Max-Age time; without one, until the browser session ends
ScopeOrigin (scheme + host + port), shared across all tabsOrigin, but separate for each tabDomain and path; can be shared with subdomains
Typical sizeAround 5 MB per origin (varies by browser)Around 5 MB per originAbout 4 KB per cookie
Sent to serverNoNoYes, automatically on matching requests
JS accessYesYesYes, unless the HttpOnly flag is set

Some important details:

  • Strings only: Web Storage (localStorage and sessionStorage) stores only strings. Objects must go through JSON.stringify and JSON.parse.
  • Synchronous API: Web Storage calls block the main thread. That is fine for small values but bad for large data. Use IndexedDB for large or structured data.
  • Main thread only: Web Storage is not available inside Web Workers or Service Workers.
  • The storage event: when localStorage changes, other tabs of the same origin receive a storage event. This can be used to sync logout across tabs. The tab that made the change does not receive it.
  • sessionStorage and duplicated tabs: duplicating a tab copies its sessionStorage at that moment. After that, the two copies are independent.
  • Cookies add network cost: every cookie is attached to every matching request, including image and script requests. Large or numerous cookies make requests heavier.

Typical use cases:

  • localStorage: UI preferences such as theme or language, and drafts.
  • sessionStorage: per-tab state such as a multi-step form in progress.
  • Cookies: data the server needs on each request, mainly session identifiers.

Example

// localStorage: persists across tabs and restarts
localStorage.setItem('theme', 'dark');
const user = { id: 7, name: 'Asha' };
localStorage.setItem('user', JSON.stringify(user));
const saved = JSON.parse(localStorage.getItem('user'));

// sessionStorage: only this tab, cleared when the tab closes
sessionStorage.setItem('step', '2');

// Cookie: sent to the server on later requests to this path
document.cookie = 'lang=en; Max-Age=86400; Path=/; Secure; SameSite=Lax';
console.log(document.cookie); // 'lang=en; ...' as one string

// React to changes made in other tabs
window.addEventListener('storage', (e) => {
  if (e.key === 'theme') applyTheme(e.newValue);
});

Common mistakes

  • Saying sessionStorage is cleared on page refresh. It survives reloads and is cleared only when the tab closes.
  • Storing objects directly with setItem. This saves the string '[object Object]' instead of the data.
  • Putting tokens or personal data in localStorage without realising that any script running on the page, including one injected through XSS, can read it.
  • Thinking cookies are only readable by the server. Without HttpOnly, document.cookie exposes them to JavaScript.

Follow-up questions

  • How would you sync a logout action across multiple open tabs?
  • When would you choose IndexedDB over localStorage?
  • Why does document.cookie = '...' add one cookie instead of replacing all of them?

Interview tip: Structure your answer around lifetime, scope, size and whether the data is sent to the server. A clear comparison on those four points is what interviewers are looking for.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More easy JavaScript questions

All easy questions →

Related Questions

‹
Q8 of 10 · JavaScript
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA