Advertisement

Browser Storage & Web APIs interview questions and answers

10 Browser Storage & Web APIs interview questions for JavaScript roles, each with a model answer, examples and likely follow-ups.

10 questions
Advertisement

10 questions

Q1 Beginner Save

What's the difference between localStorage and sessionStorage?

localStorage persists data with no expiration until explicitly cleared, and is shared across all tabs/windows for the same origin. sessionStorage only lasts for the lifetime of a single tab and is cleared when that tab closes.
localStorage.setItem('theme', 'dark');
sessionStorage.setItem('draftId', '42');
Real-world example
localStorage for remembering a user's theme preference; sessionStorage for a temporary multi-step form draft.
Likely follow-ups
  • Can other tabs read another tab's sessionStorage?
JSON & Data Serialization
Q2 Beginner Save

Why can you only store strings in localStorage, and how do you store objects?

localStorage's API only accepts and returns strings. To store objects or arrays, serialize them with JSON.stringify() before saving and JSON.parse() them back out after reading.
localStorage.setItem('user', JSON.stringify({ name: 'Sam' }));
const user = JSON.parse(localStorage.getItem('user'));
Real-world example
Caching a user's settings object client-side so the app loads instantly on return visits.
Likely follow-ups
  • What happens if the stored JSON is malformed when you try to parse it?
JSON & Data Serialization
Q3 Intermediate Save

What is the storage event and when does it fire?

The storage event fires on window in OTHER tabs/windows of the same origin whenever localStorage changes — it never fires in the tab that made the change itself. It's useful for keeping multiple open tabs in sync.
window.addEventListener('storage', (e) => {
  console.log(e.key, e.oldValue, e.newValue);
});
Real-world example
Logging a user out in every open tab the instant they log out in one tab.
Likely follow-ups
  • Does sessionStorage also trigger the storage event?
DOM & Events
Q4 Intermediate Save

What are the size limits of localStorage compared to IndexedDB?

localStorage is typically capped around 5–10MB per origin and is synchronous, which can block the main thread on large reads/writes. IndexedDB supports much larger amounts of data (often hundreds of MB or more, browser-dependent) and is fully asynchronous.
// localStorage: simple, small, synchronous
localStorage.setItem('flag', 'true');

// IndexedDB: larger, async, more setup
const request = indexedDB.open('MyDB', 1);
Real-world example
Using IndexedDB to cache an offline-capable app's entire product catalog, which wouldn't fit in localStorage.
Likely follow-ups
  • When would you choose Cache API over IndexedDB for offline data?
Memory Management & Garbage Collection
Q5 Intermediate Save

What is IndexedDB and how does it differ from a simple key-value store?

IndexedDB is a low-level, transactional NoSQL database built into the browser. It supports structured objects, indexes for fast querying by property, and versioned schema upgrades — well beyond a flat key-value store like localStorage.
const request = indexedDB.open('AppDB', 1);
request.onupgradeneeded = (e) => {
  const db = e.target.result;
  db.createObjectStore('notes', { keyPath: 'id' });
};
Real-world example
Building an offline-first note-taking app that needs to query notes by date or tag.
Likely follow-ups
  • Why does IndexedDB use events and transactions instead of simple async/await natively?
Design Patterns in JavaScript
Q6 Advanced Save

How do cookies differ from localStorage for storing data?

Cookies are automatically sent with every HTTP request to their domain (adding overhead), have a much smaller size limit (~4KB), and can be marked HttpOnly so JavaScript can't read them at all — useful for session tokens. localStorage never travels with requests and is always JS-accessible.
document.cookie = 'sessionId=abc123; Secure; SameSite=Strict';
localStorage.setItem('sessionId', 'abc123'); // different use case
Real-world example
Storing an auth session token in an HttpOnly cookie to protect it from XSS, versus storing UI preferences in localStorage.
Likely follow-ups
  • What does the SameSite cookie attribute protect against?
Security: XSS CSRF & Content Security Policy
Q7 Advanced Save

What is the Cache API and how does it relate to Service Workers?

The Cache API lets you store Request/Response pairs programmatically, most commonly from within a Service Worker, to serve assets offline or speed up repeat loads. Unlike browser HTTP caching, you fully control what's cached and for how long.
caches.open('v1').then(cache => {
  cache.addAll(['/', '/styles.css', '/app.js']);
});
Real-world example
Precaching an app's shell so it still loads (with a fallback UI) when the user is offline.
Likely follow-ups
  • How do you handle cache versioning when you deploy a new build?
Service Workers & Progressive Web Apps
Q8 Advanced Save

How does the Geolocation API work and what are its privacy implications?

navigator.geolocation.getCurrentPosition() asynchronously requests the user's location, always requiring explicit browser permission first. It should only be called after a clear user action, since silent location requests are a major privacy red flag and often blocked or flagged by browsers.
navigator.geolocation.getCurrentPosition(
  pos => console.log(pos.coords.latitude, pos.coords.longitude),
  err => console.error(err.message)
);
Real-world example
A delivery app asking for location only when the user taps "Use my current location."
Likely follow-ups
  • What's the difference between getCurrentPosition() and watchPosition()?
Networking: Fetch XHR WebSockets & CORS
Q9 Advanced Save

What does the Intersection Observer API do and why is it preferred over scroll event listeners?

IntersectionObserver asynchronously watches when a target element enters or leaves the viewport (or another container), without the performance cost of firing on every scroll event and manually computing element positions.
const observer = new IntersectionObserver((entries) => {
  entries.forEach(e => { if (e.isIntersecting) loadImage(e.target); });
});
observer.observe(document.querySelector('img.lazy'));
Real-world example
Implementing lazy-loading images or infinite scroll without janky scroll-handler performance.
Likely follow-ups
  • How would you unobserve an element once it's been handled?
Performance Optimization: Debouncing Throttling & Memoization
Q10 Advanced Save

How do you check available and used storage quota in a browser?

Use the StorageManager API's navigator.storage.estimate(), which returns a Promise resolving to an object with usage and quota (both in bytes), covering localStorage, IndexedDB, Cache API, and other origin storage combined.
const { usage, quota } = await navigator.storage.estimate();
console.log(`Using ${usage} of ${quota} bytes`);
Real-world example
Warning users before an offline-capable app runs out of storage space for cached data.
Likely follow-ups
  • What is navigator.storage.persist() used for?
Memory Management & Garbage Collection