Browser Storage & Web APIs

10 questions found

What's the difference between localStorage and sessionStorage?

Beginner
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.

Common follow-ups: Can other tabs read another tab's sessionStorage?

JSON & Data Serialization

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

Beginner
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.

Common follow-ups: What happens if the stored JSON is malformed when you try to parse it?

JSON & Data Serialization

What is the storage event and when does it fire?

Intermediate
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.

Common follow-ups: Does sessionStorage also trigger the storage event?

DOM & Events

What are the size limits of localStorage compared to IndexedDB?

Intermediate
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.

Common follow-ups: When would you choose Cache API over IndexedDB for offline data?

Memory Management & Garbage Collection

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

Intermediate
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.

Common follow-ups: Why does IndexedDB use events and transactions instead of simple async/await natively?

Design Patterns in JavaScript

How do cookies differ from localStorage for storing data?

Advanced
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.

Common follow-ups: What does the SameSite cookie attribute protect against?

Security: XSS CSRF & Content Security Policy

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

Advanced
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.

Common follow-ups: How do you handle cache versioning when you deploy a new build?

Service Workers & Progressive Web Apps

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

Advanced
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."

Common follow-ups: What's the difference between getCurrentPosition() and watchPosition()?

Networking: Fetch XHR WebSockets & CORS

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

Advanced
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.

Common follow-ups: How would you unobserve an element once it's been handled?

Performance Optimization: Debouncing Throttling & Memoization

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

Advanced
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.

Common follow-ups: What is navigator.storage.persist() used for?

Memory Management & Garbage Collection