- Home
- Interview Questions
- JavaScript
- 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
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.
| Feature | localStorage | sessionStorage | Cookies |
|---|---|---|---|
| Lifetime | Until cleared by code or the user | Until the tab or window is closed (survives reloads) | Until the Expires/Max-Age time; without one, until the browser session ends |
| Scope | Origin (scheme + host + port), shared across all tabs | Origin, but separate for each tab | Domain and path; can be shared with subdomains |
| Typical size | Around 5 MB per origin (varies by browser) | Around 5 MB per origin | About 4 KB per cookie |
| Sent to server | No | No | Yes, automatically on matching requests |
| JS access | Yes | Yes | Yes, unless the HttpOnly flag is set |
Some important details:
- Strings only: Web Storage (localStorage and sessionStorage) stores only strings. Objects must go through
JSON.stringifyandJSON.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
storageevent. 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.cookieexposes 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
Related Questions
- How do HttpOnly, Secure and SameSite cookie flags protect against XSS and CSRF? · JavaScript · 1 ans
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · JavaScript · 1 ans
- How do try, catch and finally work, and what happens if finally contains a return? · JavaScript · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · JavaScript · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- Why does a for loop with var and setTimeout print the same value every time? · JavaScript · 1 ans
- Why is using await inside a loop often slow, and how do you run async tasks in parallel? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)