JavaScript Interview Questions - Advanced Topics
30 interview questions on design patterns, memory management, Web Workers, Service Workers, performance, security, and the modern JavaScript ecosystem.
30 interview questions on design patterns, memory management, Web Workers, Service Workers, performance, security, and the modern JavaScript ecosystem. This interview-focused guide covers essential javascript interview questions - advanced topics concepts for technical interviews.
JavaScript Interview Questions – Advanced Topics
Senior-level questions covering design patterns, memory management, Web Workers, Service Workers, performance optimization, security, and the modern JS ecosystem.
1. What design patterns are commonly used in JavaScript?
- Module Pattern — Encapsulate private state using closures
- Singleton — Ensure only one instance exists
- Observer (Pub/Sub) — Event-driven communication
- Factory — Create objects without specifying exact class
- Strategy — Swap algorithms at runtime
- Decorator — Add behavior dynamically
- Proxy — Control access to another object
// Observer pattern
class EventEmitter {
constructor() { this.events = {}; }
on(e, fn) { (this.events[e] ||= []).push(fn); }
emit(e, d) { this.events[e]?.forEach(fn => fn(d)); }
}
2. How does garbage collection work in JavaScript?
JavaScript uses mark-and-sweep:
- Mark: From roots (global, locals), mark all reachable objects
- Sweep: Remove unmarked objects
Objects become eligible for GC when unreachable. Common memory leak causes: detached DOM elements with event listeners, forgotten timers, closures referencing large data.
3. What is a memory leak and how to prevent it?
A memory leak occurs when memory is allocated but never released. Common causes:
- Global variables accumulating data
- Forgotten timers/intervals
- Detached DOM elements with event listeners
- Closures holding references to large objects
- Circular references in older IE
// LEAK: Event listener keeps reference even after element removed
let el = document.getElementById("btn");
el.addEventListener("click", handler);
document.body.removeChild(el); // Leak! el still referenced in listener
// FIX: Remove listener first, then element
el.removeEventListener("click", handler);
el = null;
4. What are Web Workers?
Background threads separate from the main thread. Cannot access DOM but can perform CPU-intensive work without blocking UI.
const worker = new Worker("worker.js");
worker.postMessage(largeData);
worker.onmessage = e => console.log(e.data);
5. What are Service Workers?
Proxy between browser and network, enabling offline functionality, push notifications, and background sync. Core of PWAs.
navigator.serviceWorker.register("/sw.js");
// sw.js can intercept fetch requests and serve cached responses
6. What is CORS?
Cross-Origin Resource Sharing controls which domains can access your API from browsers. Enforced by browsers via preflight (OPTIONS) requests.
[!IMPORTANT] CORS is enforced by browsers, not servers. Server must send proper headers (
Access-Control-Allow-Origin). Server-to-server requests are NOT affected.
7. What is XSS and how to prevent it?
Cross-Site Scripting injects malicious scripts into web pages. Prevention:
- Never use
innerHTMLwith user input - Use
textContentinstead - Sanitize HTML with DOMPurify
- Set
Content-Security-Policyheaders - Escape output in templates
8. What is CSRF and how to prevent it?
Cross-Site Request Forgery tricks users into executing unwanted actions. Prevention: SameSite cookies, CSRF tokens, custom headers, Origin/Referer validation.
9. What is the difference between deep copy and shallow copy?
- Shallow: Top-level copy; nested objects share references
- Deep: Complete independent copy
// Deep copy methods
const deep1 = JSON.parse(JSON.stringify(obj)); // Loses functions, dates
const deep2 = structuredClone(obj); // Modern, handles more types
10. What is tree shaking?
Eliminates dead code (unused exports) from the final bundle. Works only with ES6 modules (static imports). Tools: Webpack, Rollup, Vite.
11. What is code splitting?
Breaking code into smaller chunks loaded on demand.
const module = await import("./heavy-module.js");
module.doSomething();
12. What is lazy loading?
Deferring loading of non-critical resources (images, components, routes) until needed.
<img loading="lazy" src="image.jpg" alt="...">
13. What is the Critical Rendering Path?
The sequence of steps the browser takes to render a page: DOM construction → CSSOM construction → Render tree → Layout → Paint. Optimizing it improves page load speed.
14. What is the difference between defer and async script loading?
defer: Downloads in parallel, executes in order after HTML parsingasync: Downloads in parallel, executes immediately when ready (order not guaranteed)
[!TIP] Use
deferfor scripts that depend on each other or DOM. Useasyncfor independent scripts (analytics, ads).
15. What is the Event Loop blocking?
Long-running synchronous code blocks the event loop, freezing the UI. Fix: break work into chunks with setTimeout, use Web Workers, use requestAnimationFrame.
16. What are micro-frontends?
Architectural pattern where a web application is composed of independent smaller apps, each owned by different teams. Tools: Module Federation, single-spa, qiankun.
17. What is the Virtual DOM?
An in-memory representation of the real DOM. React/Vue diff it against previous version and apply minimal changes. Enables declarative UI updates.
18. What is reconciliation in React?
The process of comparing the virtual DOM with the previous version to determine minimal changes needed (the "diffing" algorithm).
19. What is Server-Side Rendering (SSR)?
Rendering the initial HTML on the server instead of the browser. Benefits: faster First Contentful Paint, better SEO. Tools: Next.js, Nuxt.js.
20. What is Static Site Generation (SSG)?
Pre-rendering pages at build time. Fastest option — serves static HTML. Good for content that doesn't change per request.
21. What is hydration?
The process of attaching JavaScript event handlers to server-rendered HTML, making it interactive.
22. What is Proxy object?
Allows custom behavior for fundamental operations (property access, assignment, function calls).
const handler = {
get(target, prop) { return prop in target ? target[prop] : 0; }
};
const proxy = new Proxy({}, handler);
23. What is Reflect API?
Provides methods for interceptable JavaScript operations. Works with Proxy to forward default behavior.
24. What is the Temporal API?
New (Stage 4) date/time API replacing the flawed Date object. Immutable, timezone-aware, easier to use.
25. What is Intl API?
Internationalization API: number formatting, date formatting, collation, plural rules, list formatting.
const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" });
formatter.format(1234.56); // "1.234,56 €"
26. What is the difference between requestAnimationFrame() and setTimeout()?
rAF: Synchronized with display refresh rate (~60fps), pauses when tab inactive, better for animationssetTimeout: Fixed delay, continues when tab inactive, not frame-synced
27. What is WebAssembly (WASM)?
Binary instruction format for near-native performance in browsers. Compile languages like C/C++/Rust to run in the browser alongside JavaScript.
28. What are IndexedDB and Web Storage alternatives?
- IndexedDB: Low-level async key-value store for large structured data
- Cache API: Stores Request/Response pairs for offline use
- File System Access API: Read/write local files with user permission
29. What is Security: Content Security Policy (CSP)?
HTTP header controlling which resources the browser can load. Prevents XSS, data injection.
Content-Security-Policy: default-src 'self'; script-src 'self' trusted.com
30. What is the difference between localStorage, sessionStorage, IndexedDB, and Cache API?
| API | Capacity | Async | Structure | Use Case |
|---|---|---|---|---|
| localStorage | ~5 MB | No | Key-value | Small settings |
| sessionStorage | ~5 MB | No | Key-value | Per-tab data |
| IndexedDB | Large | Yes | Object store | Complex data |
| Cache API | Large | Yes | Request/Response | Offline PWA |