JavaScript Notes
Complete comparison of localStorage vs sessionStorage in JavaScript. Understand lifetime, scope, tab isolation, use cases, shared API, and when to choose which storage with decision chart and interview answers.
The Core Difference in One Line
localStorage remembers data forever (until you delete it). sessionStorage remembers data only until you close the tab.
Visual: How Tab Scope Works
Same API — Both Work Identically
Both storage types use exactly the same methods:
// localStorage usage
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
localStorage.removeItem('theme');
localStorage.clear();
localStorage.length;
// sessionStorage usage (identical methods!)
sessionStorage.setItem('step', '2');
const step = sessionStorage.getItem('step');
sessionStorage.removeItem('step');
sessionStorage.clear();
sessionStorage.length;
// The ONLY difference is which object you use: localStorage vs sessionStorageDecision Chart — Which One to Use?
Use Case Matching
| Use Case | Best Choice | Why |
|---|---|---|
| Dark mode preference | localStorage | Should persist across sessions |
| User language preference | localStorage | User expects it to be remembered |
| Shopping cart | localStorage | Should persist between sessions |
| Auth token (risky!) | localStorage | Needs to persist for auto-login |
| Multi-step form progress | sessionStorage | Only needed for this checkout flow |
| Search filters in current session | sessionStorage | Temporary, tab-specific |
| Unsaved form draft | sessionStorage | Protect against accidental refresh |
| Active wizard step number | sessionStorage | Tab-specific progress |
| Anonymous analytics page views | sessionStorage | Session-based counting |
Code Comparison: Persistent vs Session Data
// localStorage scenario:
// Visit 1: sets wizardStep = "2"
// Tab closed → data survives
// Visit 2: getItem('wizardStep') → "2" (stale data!)
// sessionStorage scenario:
// Visit 1: sets wizardStep = "2"
// Tab closed → data cleared automatically
// Visit 2: getItem('wizardStep') → null (clean start ✅)The storage Event (localStorage Only)
// ⚠️ The 'storage' event only works for localStorage, NOT sessionStorage!
// It fires in other tabs when localStorage changes.
// In Tab 1: listen for changes made by Tab 2
window.addEventListener('storage', function(event) {
console.log('Key changed:', event.key);
console.log('Old value:', event.oldValue);
console.log('New value:', event.newValue);
if (event.key === 'theme') {
// Another tab changed the theme — sync this tab too
document.body.className = event.newValue;
}
});
// In Tab 2: make a change
localStorage.setItem('theme', 'light'); // Tab 1 gets the storage event!
// sessionStorage does NOT fire this event — tabs are isolated
sessionStorage.setItem('anything', 'value'); // No event in other tabsCommon Mistakes
❌ Mistake 1: Using sessionStorage for data that should persist
// ❌ User expects their preference to be remembered next visit
sessionStorage.setItem('theme', 'dark');
// User closes tab → theme reset to default. Frustrating!
// ✅ Use localStorage for preferences
localStorage.setItem('theme', 'dark');❌ Mistake 2: Using localStorage for tab-specific state
// ❌ User opens two checkout tabs simultaneously
localStorage.setItem('checkoutStep', '3'); // Tab 1 is on step 3
// Tab 2 also sets checkoutStep
localStorage.setItem('checkoutStep', '1'); // Tab 2 is on step 1
// Tab 1 now reads step 1 — confused! They share the same storage.
// ✅ Use sessionStorage for tab-specific flows
sessionStorage.setItem('checkoutStep', '3'); // Tab 1's own isolated data❌ Mistake 3: Relying on sessionStorage to persist cross-page for opened links
// In page A:
sessionStorage.setItem('referrer', 'homepage');
// User clicks a link that opens in a NEW TAB (target="_blank")
// The new tab gets an EMPTY sessionStorage — data not shared!
// (Exception: duplicated tabs DO inherit a copy at duplication time)Interview Questions
Q1. What is the main difference between localStorage and sessionStorage? > The data lifetime and scope. localStorage persists permanently (until explicitly cleared) and is shared across all tabs of the same origin. sessionStorage persists only for the current tab session — data is cleared when the tab is closed, and it's completely isolated to that one tab.
Q2. Does sessionStorage persist through page refreshes? > Yes! A page refresh (F5, navigation) within the same tab keeps sessionStorage intact. Only closing the tab destroys the data.
Q3. Can two tabs on the same site share sessionStorage? > No. Each tab has its own isolated sessionStorage. Use localStorage for sharing data between tabs. For real-time updates, combine localStorage with the storage event.
Q4. Which storage type has the storage event? > Only localStorage triggers the storage event (in other tabs). sessionStorage changes do not trigger any cross-tab events because each tab is isolated.
Q5. You're building a multi-step checkout. Which storage would you use? > sessionStorage — because the checkout data is tab-specific and should be cleared when the user closes the tab (preventing stale data on the next visit). If the user has two checkout flows in two tabs, they should be independent.
Q6. What happens to sessionStorage when you duplicate a tab (Ctrl+D)? > The new tab inherits a copy of the original tab's sessionStorage at that moment. After duplication, they are independent — changes in one don't affect the other. This is different from opening a new tab with the same URL, which starts with empty sessionStorage.
Key Takeaways
✅ localStorage = permanent storage (survives everything)
✅ sessionStorage = tab-session storage (dies when tab closes)
✅ Both have identical API: setItem, getItem, removeItem, clear
✅ sessionStorage is tab-isolated — each tab has its own independent storage
✅ localStorage is shared across all tabs of the same origin
✅ Page refresh keeps sessionStorage; tab close destroys it
✅ 'storage' event = localStorage only, fires in other tabs
✅ Use localStorage for: user preferences, auth tokens, cart
✅ Use sessionStorage for: multi-step forms, temp session state, tab-specific dataExam Focus
Revise definitions, diagrams, examples, and short-answer points for localStorage vs sessionStorage - JavaScript Web Storage Comparison Guide.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, dom, localstorage, sessionstorage
Related JavaScript Master Course Topics