Web API & Performance


151) What is the DOM in one practical sentence?

Answer: The DOM is the browser’s live object model of the HTML—JS changes it, and the browser turns those changes into pixels.


152) DOM vs HTML string — why not just edit innerHTML everywhere?

Answer: innerHTML re-parses HTML, can wipe event listeners, and increases XSS risk. Direct DOM APIs (createElement, append) are safer and often more efficient for targeted changes.


153) What is “reflow” (layout) and why should you care?

Answer: Reflow is when the browser recalculates element sizes/positions. It’s expensive—doing it repeatedly causes UI lag (jank), especially in scroll/resize handlers.


154) What is “repaint” and how is it different from reflow?

Answer: Repaint redraws pixels (colors, shadows) without recalculating layout. Reflow is generally more expensive than repaint.


155) What causes layout thrashing?

Answer: Alternating DOM reads that force layout (like offsetHeight) with DOM writes (like changing styles) in a tight loop. The browser keeps re-calculating layout repeatedly.


156) How do you avoid layout thrashing?

Answer: Batch reads and writes separately, or use requestAnimationFrame to coordinate updates.


157) What’s the difference between querySelector and getElementById?

Answer: getElementById is direct and fast for IDs; querySelector is CSS-selector based and more flexible but can be slower for complex selectors.


158) NodeList vs HTMLCollection — why does it matter?

Answer: Some collections are live (HTMLCollection updates automatically) and some are static (often NodeList from querySelectorAll). Live collections can surprise you during loops.


159) Why is documentFragment useful?

Answer: It’s like building a LEGO set off-screen . You append many nodes to a fragment, then attach once → fewer reflows.


160) How does event bubbling work?

Answer: Events travel from the target node up through ancestors. This is why a click on a button can be handled by a parent container too.


161) What is event capturing?

Answer: The opposite direction: event travels from root down to the target before bubbling back up. You can listen in capture phase with { capture: true }.


162) What is event delegation and why is it powerful?

Answer: Attach one listener on a parent and handle events from children using bubbling. It reduces listeners and works for dynamically added elements.


163) When does delegation fail?

Answer: When events don’t bubble (some don’t), or when you rely on e.target without using closest() and hit nested elements unexpectedly.


164) What’s the difference between e.target and e.currentTarget?

Answer:

  • target: the actual element clicked

  • currentTarget: the element that owns the listener This matters a lot in delegation.


165) Why should you care about passive event listeners?

Answer: For scroll/touch events, { passive: true } tells the browser you won’t call preventDefault, letting it scroll smoothly without waiting for JS.


166) What is debouncing (in human terms)?

Answer: “Wait until the user stops doing the thing.” Example: user types 10 keys—run search once after they pause.


167) What is throttling (in human terms)?

Answer: “Run at most once every X ms no matter how crazy the events fire.” Great for scroll/resize.


168) Debounce vs Throttle — when do you choose which?

Answer:

  • Debounce: search input, autosave, validation (after pause)

  • Throttle: scroll position, resize, mousemove (keep updating, but not too often)


169) Why is requestAnimationFrame often better than setTimeout for UI?

Answer: requestAnimationFrame syncs with the browser’s paint cycle (usually ~60fps), preventing wasted work and smoother animations.


170) What is the critical rendering path?

Answer: The steps from HTML/CSS/JS to pixels: parse → build DOM/CSSOM → layout → paint → composite. Blocking any step (big JS, huge CSS) delays display.


171) What are “long tasks” and why do they hurt UX?

Answer: JS tasks > ~50ms block the main thread. The user feels it as input delay or jank. Break work into chunks or use workers.


172) What’s a Web Worker and when should you use it?

Answer: A worker runs JS on a background thread. Use it for CPU-heavy work (parsing, compression, large computations) so the UI stays responsive.


173) Why can’t Web Workers access the DOM?

Answer: DOM is not thread-safe. The browser keeps DOM on the main thread to avoid race conditions. Workers communicate via postMessage.


174) What’s the difference between localStorage and sessionStorage?

Answer: Both are synchronous key-value storage. localStorage persists across tabs and restarts; sessionStorage is per-tab and cleared when the tab closes.


175) Why is localStorage considered bad for performance-sensitive code?

Answer: It’s synchronous and blocks the main thread. Frequent reads/writes can cause jank. Prefer IndexedDB for larger or frequent operations.


176) What is IndexedDB in one line?

Answer: A browser database for structured data—async, large storage, and better for production-scale caching than localStorage.


177) What is a memory leak in the browser world?

Answer: Memory leak = memory that should be freed but stays reachable. Example: event listeners, timers, or closures holding references to big objects.


178) Name 3 common causes of memory leaks in frontend apps.

Answer:

  1. Not removing event listeners

  2. Uncleared intervals/timeouts

  3. Caching DOM nodes or large data in long-lived closures/global variables


179) How does an event listener cause a memory leak?

Answer: If a listener references an object, that object stays alive as long as the listener is attached. If you remove the DOM node but keep listener references, memory can remain retained.


180) Why can setInterval be dangerous?

Answer: It keeps running until cleared. If it captures state or updates DOM repeatedly, it leaks memory and burns CPU.


181) What is a detached DOM node?

Answer: A node removed from the document but still referenced by JS. It can’t be garbage-collected until all JS references are gone—classic leak source.


182) What is the fastest way to reduce unnecessary DOM updates?

Answer: Avoid frequent re-renders and batch changes (fragments, minimal diffs). In frameworks: memoization, virtualization, and avoiding state changes on every pixel of scroll.


183) What is list virtualization and why is it important?

Answer: Rendering only what’s visible (like 30 rows instead of 30,000). Huge performance win for big lists and tables.


184) What is XSS in simple terms?

Answer: XSS is when attackers inject malicious JS into your page—so your site runs their code with your user’s permissions.


185) What’s the #1 cause of XSS in frontend code?

Answer: Inserting untrusted content into the DOM as HTML (innerHTML, unsafe templates). If user input becomes HTML, attackers can execute scripts.


186) How do you prevent XSS properly?

Answer:

  • Escape/sanitize untrusted input

  • Prefer text insertion (textContent) over HTML

  • Use trusted sanitizers (DOMPurify) when HTML is required

  • Strong CSP (Content Security Policy)


187) Why is textContent safer than innerHTML?

Answer: textContent inserts plain text, not HTML, so scripts/markup are not interpreted.


188) What is CORS and what problem does it solve?

Answer: CORS controls which origins can read responses from another origin. It’s a browser-enforced security policy to prevent random websites from reading your APIs.


189) Is CORS a security feature for your server?

Answer: It protects browsers , not your server. Attackers can still call your API from curl/Postman. Real security is auth, tokens, and server-side checks.


190) What is a preflight request and why does it happen?

Answer: For “non-simple” cross-origin requests, the browser sends an OPTIONS request first to ask permission (methods/headers). It prevents unsafe cross-origin actions.


191) What makes a request “simple” vs “non-simple” in CORS terms?

Answer: Simple uses safe methods (GET/POST) with restricted headers and content types. Adding custom headers (like Authorization) typically triggers preflight.


192) What is CSRF and how is it different from XSS?

Answer:

  • XSS: attacker runs code in your site

  • CSRF: attacker tricks the browser into making authenticated requests to your site using stored cookies Defense differs: CSRF tokens, SameSite cookies, etc.


193) How do SameSite cookies help against CSRF?

Answer: They restrict cookies from being sent on cross-site requests, reducing CSRF risk. SameSite=Lax/Strict blocks many cross-origin form submits.


194) What is clickjacking?

Answer: A malicious site overlays your page in an invisible iframe, tricking users into clicking buttons. Defense: X-Frame-Options or CSP frame-ancestors.


195) What is a Content Security Policy (CSP) and why is it powerful?

Answer: CSP tells the browser which scripts/resources are allowed. Even if XSS slips in, CSP can block inline scripts or untrusted sources, reducing damage.


196) What is “performance budget” in frontend work?

Answer: A set of limits (JS size, load time, LCP, etc.). It forces decisions: split code, compress assets, reduce third-party scripts.


197) What’s the difference between defer and async on script tags?

Answer:

  • defer: download in parallel, execute in order after HTML parsed

  • async: download in parallel, execute as soon as ready (order not guaranteed) defer is usually safer for app scripts.


198) Why can third-party scripts kill performance?

Answer: They add network cost, parse/execute time, and can block main thread. If they run long tasks, they delay interaction and rendering.


199) What is caching (HTTP) and why does it help?

Answer: Caching reuses previous responses (via Cache-Control, ETag). It reduces network trips and speeds repeat visits—huge real-world win.


200) If a page feels slow, what’s a practical debugging approach?

Answer:

  1. Use DevTools Performance to find long tasks

  2. Check Network: big bundles, slow images, third-party scripts

  3. Reduce DOM work, avoid layout thrash, debounce input

  4. Split code, lazy-load routes, virtualize lists

  5. Offload heavy CPU to workers


If you want, I can also generate a “super quick revision sheet” from these 200 (just 1–2 line bullets + key code patterns).

Last updated