Interview Q&A · JavaScript · 14 questions in this topic
DOM, Events & Browser APIs — JavaScript Interview Q&A
Frontend runtime — selecting and mutating the DOM, event flow, forms and storage. Part of DOM & Browser · 204 questions in the JavaScript bank.
How do you select and modify DOM elements?
Answer
querySelector(All) with CSS selectors (modern default), getElementById for ids; modify via textContent (safe text), classList (classes), setAttribute, and style. Batch reads/writes to avoid layout thrash; prefer textContent over innerHTML (XSS safety).
textContent-for-text, classList-for-style is the safe-manipulation duo.
Example
const el = document.querySelector('#app'); el.textContent = 'safe text'; // no HTML parsing (XSS-safe) el.classList.toggle('open');
How do capturing and bubbling work (event phases)?
Answer
Events travel capture (window→target) then bubble (target→window); listeners default to bubble, { capture: true } catches descending. stopPropagation halts travel; preventDefault cancels default action (orthogonal concerns). Target vs currentTarget distinguishes origin from handling node.
Capture-down, bubble-up, target-in-middle is the phase picture.
Key points
- 1Capture — descending, opt-in.
- 2Target — at the node.
- 3Bubble — ascending, default.
Example
el.addEventListener('click', handler); // bubble (default) document.addEventListener('click', h2, { capture: true }); // descending
💡 stopPropagation-vs-preventDefault is the distinction to nail.
What is event delegation and why is it better?
Answer
One listener on a parent handles events from many children via event.target matching — fewer listeners, automatic coverage of dynamic nodes, less memory. Tables/lists/menus delegate; closest() finds the semantic ancestor.
Single-parent-listener-plus-target-match is the pattern.
Example
list.addEventListener('click', (e) => { const item = e.target.closest('li'); // semantic ancestor if (item) handle(item.dataset.id); });
💡 Dynamic-nodes-covered-free is the delegation payoff.
How do you remove listeners (and avoid leaks)?
Answer
removeEventListener needs the same function reference (named handlers or stored variables — anonymous arrows cannot detach). { once: true } auto-removes single-fire handlers; AbortController signals bulk-remove groups.
Same-reference-or-it-stays is the removal law.
Example
const onClick = () => {}; el.addEventListener('click', onClick); el.removeEventListener('click', onClick); // same ref required // el.addEventListener('x', handler, { signal }); // bulk abort
How do forms work (submit, validation, FormData)?
Answer
Submit events (preventDefault for SPA handling), Constraint Validation API (required/pattern + setCustomValidity + reportValidity), FormData serializes entries (including files) for fetch. Uncontrolled (FormData read) vs controlled (state-bound) is the architecture split.
Native-validation-first plus FormData-serialize is the modern minimal stack.
Example
form.addEventListener('submit', (e) => { e.preventDefault(); const data = new FormData(form); // entries incl. files fetch('/api', { method: 'POST', body: data }); });
What are `localStorage`, `sessionStorage`, cookies and IndexedDB for?
Answer
localStorage: persistent string key-values (~5MB, sync — small UI state). sessionStorage: per-tab lifetime. Cookies: tiny, server-visible (httpOnly/secure/sameSite for session tokens). IndexedDB: async structured bulk storage (offline data).
Tokens-in-httpOnly-cookies, UI-prefs-in-localStorage, bulk-offline-in-IDB is the placement map.
Key points
- 1localStorage — persistent small UI state.
- 2Cookies — server-visible session tokens.
- 3IndexedDB — async bulk offline data.
Example
localStorage.setItem('theme', 'dark'); // strings only (JSON for objects)
How do you prevent XSS (cross-site scripting)?
Answer
Treat all user data as text (textContent, not innerHTML), escape/parameterize by context, enforce Content-Security-Policy (script-src restrictions), sanitize rich HTML (DOMPurify) when markup is required, and flag cookies httpOnly (stolen-cookie defense).
Text-by-default plus CSP is the layered defense.
Key points
- 1Output — textContent, sanitizers for rich HTML.
- 2Policy — CSP headers.
- 3Cookies — httpOnly + secure + sameSite.
Example
// el.textContent = userInput; // safe // el.innerHTML = userInput; // stored XSS!
💡 Context-aware-output-encoding is the principle behind every rule.
How does the browser render (critical path, reflow vs repaint)?
Answer
Parse HTML/CSS → render tree → layout (geometry) → paint → composite. Reflow (geometry changes: width, display) is costliest; repaint (color) cheaper; composite-only (transform, opacity) cheapest — animate those two. Batch DOM writes, read-then-write separated, transform/opacity animations.
Composite-only-animation is the 60fps rule.
Key points
- 1Reflow — geometry, expensive.
- 2Repaint — pixels, moderate.
- 3Composite — layers, cheap.
Example
// cheap: transform/opacity // el.style.transform = `translateX(${x}px)`;
💡 Animate-transform-and-opacity is the performance mantra.
How do `IntersectionObserver` and `ResizeObserver` beat scroll handlers?
Answer
Observers push notifications (visibility, size) on the browser's schedule — no per-scroll JS, no thrash, offscreen-throttled. IntersectionObserver drives lazy-load/infinite-scroll/impression tracking; ResizeObserver drives responsive components.
Observe-don't-poll is the efficiency principle.
Example
const io = new IntersectionObserver((entries) => { entries.forEach((e) => { if (e.isIntersecting) load(e.target); }); });
What is the difference between `load`, `DOMContentLoaded` and `defer`?
Answer
DOMContentLoaded fires after HTML parsed (DOM ready, scripts/deferred done) — the interaction-ready signal. load waits for all resources (images, iframes) — the fully-loaded signal. defer scripts run post-parse in order; async scripts run whenever fetched.
Defer-by-default for app scripts; DOMContentLoaded for init logic.
Key points
- 1DOMContentLoaded — parsed, interactive.
- 2load — everything fetched.
- 3defer — ordered post-parse scripts.
Example
<!-- <script src='app.js' defer></script> -->
How do history, location and navigation APIs work (SPA routing)?
Answer
pushState/replaceState change URLs without reloads (popstate on back/forward); location reads/parses current URL; hash-routing (no server config) vs history-routing (needs server fallback to index.html).
History-API-plus-server-fallback is the SPA routing contract.
Example
history.pushState({ page: 2 }, '', '/page/2'); window.addEventListener('popstate', render); // back/forward
How do web workers move work off the main thread?
Answer
Workers run scripts on separate threads (no DOM access) communicating via postMessage (structured-clone/transferable payloads). Dedicated workers serve one page; SharedWorkers span contexts; worklets cover paint/audio threads.
Transferables (buffers) move zero-copy; heavy compute/parsing belongs here.
Example
// const w = new Worker('calc.js'); // w.postMessage(data); // cloned or transferred // w.onmessage = (e) => render(e.data);
💡 No-DOM-plus-message-passing is the worker constraint set.
What are viewport, responsive design and media queries?
Answer
Viewport meta makes layout match device width; fluid layouts (flex/grid, clamp()) adapt continuously; media queries restyle at breakpoints. Mobile-first CSS (base small, min-width up) keeps the common path lean.
Meta-plus-fluid-plus-breakpoints is the responsive trio.
Example
<!-- <meta name='viewport' content='width=device-width, initial-scale=1'> -->
How do you make the DOM accessible (a11y essentials)?
Answer
Semantic HTML (button/nav/main over divs), labels for inputs, focus management (visible focus, trap in modals), ARIA for custom widgets (roles/states), alt text, keyboard operability, and contrast. Accessibility is correctness for all input modalities — test with keyboard-only plus a screen reader.
Semantics-first-plus-keyboard-complete is the a11y baseline.
Key points
- 1Semantics — native elements over divs.
- 2Keyboard — everything reachable and operable.
- 3ARIA — custom-widget contracts.
Recommended resourcesAffiliate links · may earn us a commission