Skip to the content.

Frontend Interview Questions and Answers: HTML, CSS, JavaScript, Browsers and Performance (2027)

frontend-interview-questions is a free, practical list of frontend interview questions with clear answers for frontend and full-stack developer interviews. It covers HTML and semantics, accessibility, CSS layout and modern CSS, JavaScript in the browser, how browsers render pages, web performance and Core Web Vitals, networking and caching, web security, frameworks (React, Vue, Angular, Svelte) and state management, testing, tooling, and the frontend system design round. Each answer is short enough to say out loud and points to primary sources (MDN, web.dev, W3C) so you can go deeper.

Last reviewed: December 2026. Browser support notes reflect the web platform as of late 2026. Before using a newer feature in production, check its Baseline status on MDN or Can I use.

Table of Contents

How to Use This List

What Frontend Interviews Look Like

Round What happens How to prepare
Recruiter or hiring manager screen Background, motivation, role fit Two-minute story of your best frontend project
Trivia / knowledge screen Rapid questions like the ones in this list Sections 1 to 10
JavaScript coding Implement a utility (debounce, Promise.all, deep clone, event emitter) The companion JavaScript repo’s src/ folder
UI coding Build a component in 45 to 60 minutes: autocomplete, modal, tabs, star rating, infinite list Section 15; practice with plain DOM and your framework
Algorithms LeetCode-style problem, usually easier than backend roles Arrays, strings, hash maps, trees (DOM trees!)
Frontend system design Design a news feed, chat app, photo grid, or autocomplete end to end Section 14
Behavioral Collaboration with designers and backend, conflict, ownership STAR stories

Company mixes vary: some skip algorithms entirely, others skip UI coding. Ask the recruiter what each round covers; that is normal and expected.

A 4-Week Preparation Plan

Week Focus Done when you can…
1 HTML, accessibility, CSS fundamentals and layout (sections 1 to 4) Build a responsive, keyboard-accessible card grid and navbar without a framework
2 Modern CSS, DOM, browser internals (sections 5 to 7) Explain the critical rendering path and what triggers layout vs paint vs composite
3 Performance, networking, security (sections 8 to 10) Audit a real site with Lighthouse and DevTools and explain each fix
4 Frameworks, state, testing, system design, UI coding (sections 11 to 15) Build an accessible autocomplete in 45 minutes and design a news feed on a whiteboard

1. HTML and Semantics

Q1. What does <!DOCTYPE html> do? [J]

It tells the browser to render the page in standards mode. Without it, browsers fall back to “quirks mode”, which emulates old browser bugs (for example a different box model for some elements) and makes layout unpredictable.

Q2. What is semantic HTML and why does it matter? [J]

Using elements for their meaning rather than their look: <header>, <nav>, <main>, <article>, <section>, <aside>, <footer>, <button>, <h1> to <h6>, <ul>, <table> for tabular data. Benefits:

A <div onclick> pretending to be a button is the classic counterexample.

Q3. <section> vs <article> vs <div>? [J]

<article> is self-contained content that would make sense on its own (a blog post, a comment, a product card). <section> is a thematic group of content, usually with a heading. <div> has no meaning and is for styling or scripting hooks only.

Q4. What are data-* attributes? [J]

Custom attributes for storing extra data on elements: <li data-id="42">. Read them in JavaScript with el.dataset.id and select them in CSS with [data-id="42"]. Do not store anything sensitive; it is visible in the HTML.

Q5. What is the difference between <script>, <script async> and <script defer>? [J]

A plain script blocks HTML parsing while it downloads and runs. async downloads in parallel and runs as soon as it arrives, in no particular order; good for independent scripts like analytics. defer downloads in parallel and runs after parsing, in document order; good for app code. type="module" scripts are deferred by default.

Q6. What goes in the <head>, and which meta tags matter? [J]

<meta charset="utf-8"> (first, so the parser decodes correctly), <meta name="viewport" content="width=device-width, initial-scale=1"> (required for responsive layouts on mobile), <title>, <meta name="description">, <link rel="canonical">, Open Graph tags for link previews, stylesheets, preloads and icons.

Q7. How do <img> srcset, sizes and <picture> work? [M]

srcset lists image files with their widths (photo-480.jpg 480w, photo-960.jpg 960w), and sizes tells the browser how wide the image will be displayed ((max-width: 600px) 100vw, 50vw). The browser picks the smallest file that looks sharp for the screen’s pixel density. <picture> with <source> elements is for art direction (different crops at different sizes) or format fallback (AVIF, then WebP, then JPEG). Always set width and height attributes so the browser reserves space and avoids layout shift, and add loading="lazy" to below-the-fold images.

Q8. How do forms work without JavaScript? [J]

A <form action method> submits named fields (name attribute) to the server. Built-in validation (required, type="email", min, max, pattern) blocks submission and shows browser messages; the :invalid and :user-invalid pseudo-classes let you style errors. Always pair inputs with <label for> (or wrap them in the label). Client-side validation is a UX feature only; the server must validate again.

Q9. What are the <dialog> element and the Popover API? [M]

<dialog> opened with showModal() gives you a real modal: focus moves into it, the rest of the page becomes inert, Escape closes it, and ::backdrop styles the overlay. The Popover API (popover attribute plus popovertarget on a button) creates non-modal overlays such as menus and tooltips that render in the top layer, close on outside click or Escape (“light dismiss”), and need no JavaScript. Both remove a lot of hand-written focus and z-index code.

2. Accessibility (a11y)

Q10. What is WCAG, and what level do companies target? [J]

The Web Content Accessibility Guidelines from the W3C. The current version is WCAG 2.2 (2023). Criteria are grouped under four principles, POUR: Perceivable, Operable, Understandable, Robust. Most organizations and many laws target level AA. Examples: text contrast of at least 4.5:1 (3:1 for large text), everything usable by keyboard, visible focus, and (new in 2.2) a minimum target size for pointer targets.

Q11. What is ARIA, and what is the first rule of ARIA? [M]

ARIA (Accessible Rich Internet Applications) attributes add roles, states and properties for assistive technology: role="tablist", aria-expanded, aria-controls, aria-live. The first rule: do not use ARIA if a native HTML element does the job. A <button> is better than <div role="button" tabindex="0"> plus key handlers. Wrong ARIA is worse than none, because it tells screen readers something false. The ARIA Authoring Practices Guide shows correct patterns for tabs, comboboxes, menus and dialogs.

Q12. How do you make a custom component keyboard accessible? [M]

Q13. How do you hide content visually but keep it for screen readers, and vice versa? [M]

Visually hidden but announced: a “visually-hidden” utility class (absolute positioning, 1px size, clip-path: inset(50%), overflow: hidden). Hidden from everyone: display: none, hidden attribute, visibility: hidden. Visible but hidden from assistive tech: aria-hidden="true" (never on focusable elements). inert makes a whole subtree non-interactive and hidden from assistive tech.

Q14. What are live regions? [M]

Elements with aria-live="polite" (or role="status") announce changes to their text to screen reader users without moving focus, for messages like “Saved” or “3 results found”. aria-live="assertive" (or role="alert") interrupts and should be reserved for urgent errors. The region must exist in the DOM before the content changes.

Q15. How do you test accessibility? [J]

Automated checks (axe DevTools, Lighthouse) catch a portion of issues, such as missing labels and low contrast. Then test manually: navigate with only the keyboard, zoom to 200% and 400%, use a screen reader (VoiceOver on macOS and iOS, NVDA on Windows, TalkBack on Android), and check with reduced motion and forced colors turned on.

3. CSS Fundamentals

Q16. Explain the box model. What does box-sizing: border-box change? [J]

Every element is a box of content, padding, border and margin. With the default content-box, width sets only the content width, so padding and border make the box wider. With border-box, width includes padding and border, which makes sizing predictable. Most resets apply *, *::before, *::after { box-sizing: border-box; }.

Q17. How does specificity work? [J]

When rules conflict, the browser compares, in order: origin and importance (!important), cascade layers, specificity, then source order (later wins). Specificity is counted as (IDs, classes/attributes/pseudo-classes, elements/pseudo-elements):

Selector Specificity
p (0, 0, 1)
.card p (0, 1, 1)
#main .card p:hover (1, 2, 1)
:where(.card) p (0, 0, 1), because :where() counts as zero
:is(#main, .card) p (1, 0, 1), because :is() takes its most specific argument

Inline styles beat selectors. Keep specificity low and flat (single classes) to avoid escalation wars.

Q18. What are cascade layers (@layer)? [M]

@layer reset, base, components, utilities; declares layers in priority order, later layers winning. Specificity only matters within a layer, so a simple utility class in a later layer beats a highly specific selector in an earlier layer. Unlayered styles beat all layered styles. Layers make it easy to integrate third-party CSS without fighting its selectors.

Q19. What is the difference between display: none, visibility: hidden and opacity: 0? [J]

  Takes space Clickable Read by screen readers Animatable
display: none No No No Not traditionally (newer transition-behavior: allow-discrete helps)
visibility: hidden Yes No No Yes (discretely)
opacity: 0 Yes Yes Yes Yes

Q20. Explain position values. [J]

static (default, normal flow), relative (offset from its normal place, keeps its space, becomes a containing block for absolute children), absolute (removed from flow, positioned against the nearest positioned ancestor), fixed (positioned against the viewport, unless an ancestor has a transform, filter or similar, which then becomes the containing block), sticky (acts relative until a scroll threshold, then sticks within its scroll container; it fails if an ancestor has overflow: hidden).

Q21. What is a stacking context, and why does my z-index: 9999 not work? [M]

A stacking context is a group of elements that are layered together and then placed as a single unit in their parent context. It is created by the root, positioned elements with a z-index other than auto, opacity below 1, transform, filter, isolation: isolate, will-change, flex and grid children with z-index, and more. A child’s z-index only competes inside its own context, so z-index: 9999 inside a parent with z-index: 1 can still sit below a sibling with z-index: 2. The top layer (<dialog>, popovers) sits above everything and avoids the problem.

Q22. What is margin collapsing? [M]

Vertical margins of adjacent block elements combine into the larger of the two instead of adding up. It also happens between a parent and its first or last child when nothing (border, padding, inline content) separates them. It does not happen in flex or grid containers, or with horizontal margins. Using gap in flex and grid avoids the issue.

Q23. em vs rem vs px vs viewport units? [J]

px is fixed. em is relative to the element’s own font size (compounding when nested). rem is relative to the root font size, so it respects the user’s browser font setting; use it for font sizes and most spacing. vw/vh are percentages of the viewport. On mobile, 100vh can be taller than the visible area because of browser toolbars; use 100dvh (dynamic), svh (small) or lvh (large). ch is the width of the “0” glyph, handy for line length (max-width: 65ch).

Q24. What are pseudo-classes and pseudo-elements? [J]

Pseudo-classes select elements in a state: :hover, :focus-visible, :checked, :nth-child(2n), :not(), :has(). Pseudo-elements style a part of an element or generated content: ::before, ::after, ::placeholder, ::marker, ::selection, ::backdrop.

Q25. What are CSS custom properties, and how do they differ from Sass variables? [J]

--brand: #0a7; used with var(--brand, fallback). They are live at runtime, inherit through the DOM, can be changed with media queries or JavaScript (el.style.setProperty('--brand', 'red')), and power theming like dark mode. Sass variables are compiled away and are static. @property registers a custom property with a type, which lets you animate it.

4. Layout: Flexbox, Grid and Responsive Design

Q26. Flexbox vs Grid: when do you use each? [J]

Flexbox lays items out in one dimension, letting content size drive the layout: navbars, button groups, centering, rows of tags that wrap. Grid lays out in two dimensions with explicit rows and columns: page layouts, card galleries, dashboards, forms with aligned labels. They combine well (a grid of cards, each card using flex inside).

Q27. How do you center an element horizontally and vertically? [J]

.parent { display: grid; place-items: center; }
/* or */
.parent { display: flex; justify-content: center; align-items: center; }

For an absolutely positioned element: inset: 0; margin: auto; with a set width and height. In block layout, align-content: center now also works in many current browsers; check support before relying on it.

Q28. Explain flex: 1. [M]

Shorthand for flex-grow: 1; flex-shrink: 1; flex-basis: 0%. The item starts from zero size and takes an equal share of the free space. flex: auto uses flex-basis: auto, so items start from their content size and share only the leftover space. A common bug: long words or wide children refuse to shrink because flex items default to min-width: auto; set min-width: 0 on the item.

Q29. Write a responsive card grid with no media queries. [M]

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(min(16rem, 100%), 1fr));
  gap: 1rem;
}

auto-fill creates as many 16rem-or-wider columns as fit; min(16rem, 100%) prevents overflow on very small screens. auto-fit collapses empty tracks so a few items stretch to fill the row.

Q30. What is mobile-first design? [J]

Write base styles for small screens, then add @media (min-width: ...) rules for larger ones. Small screens get less CSS to override, and the habit forces you to prioritize content. Combine it with fluid techniques (clamp(), flexible grids) so fewer breakpoints are needed.

Q31. What are container queries? [M]

Media queries respond to the viewport; container queries respond to the size of a parent container, so a component can adapt to wherever it is placed (sidebar vs main column).

.card-wrapper { container-type: inline-size; }
@container (min-width: 30rem) {
  .card { display: grid; grid-template-columns: 10rem 1fr; }
}

Container query units (cqi, cqw) size things relative to the container. Size container queries are widely supported in current browsers.

Q32. What is subgrid? [M]

grid-template-columns: subgrid (or rows) makes a nested grid reuse its parent’s tracks, so content inside different cards (titles, bodies, buttons) lines up across cards. It is supported in all major current browsers.

Q33. How do you do fluid typography? [M]

font-size: clamp(1rem, 0.8rem + 1vw, 1.5rem); grows with the viewport but stays within bounds. Keep a rem component in the middle value so the text still scales with the user’s zoom and font settings.

5. Modern CSS

Q34. What does :has() do? [M]

A relational (“parent”) selector: .card:has(img) selects cards that contain an image; form:has(:user-invalid) button styles a submit button when the form has invalid fields; label:has(+ input:checked) styles a label whose next sibling is checked. It replaces many small scripts that toggled classes. It is Baseline across major browsers.

Q35. Is native CSS nesting supported? [J]

Yes. Nesting works in all major current browsers:

.card {
  padding: 1rem;
  & .title { font-weight: 600; }
  &:hover { box-shadow: 0 2px 8px rgb(0 0 0 / 0.2); }
  @media (width > 40rem) { padding: 2rem; }
}

It differs from Sass in edge cases (for example, you cannot concatenate selectors like &__title).

Q36. What are view transitions? [S]

The View Transitions API animates between two DOM states. document.startViewTransition(() => updateDom()) captures the old and new states and cross-fades them by default; give elements a view-transition-name to animate them individually (a thumbnail growing into a hero image). Same-document transitions work in single-page apps; cross-document transitions for multi-page sites are opted into with @view-transition { navigation: auto; } and have narrower support. Check MDN for current support and respect prefers-reduced-motion.

Q37. What is CSS anchor positioning? [S]

It positions an element relative to another element (its anchor) without JavaScript: the anchor gets anchor-name: --btn, the floating element uses position-anchor: --btn and position-area: bottom or the anchor() function, and position-try fallbacks flip it when there is no room. Combined with the Popover API, it covers tooltips and dropdown menus that previously needed libraries like Floating UI. It became available in all major browser engines in January 2026 (Firefox 147 was the last), so it is now “Baseline newly available”; keep a fallback if you support older browsers.

Q38. What are some other newer CSS features worth knowing? [M]

Feature What it does
@layer Cascade layers (Q18)
@scope Limits styles to a DOM subtree with an optional lower bound
@starting-style Defines the “from” style for entry animations, including from display: none
color-mix(), oklch(), relative color syntax Perceptual colors and computed palettes
light-dark() + color-scheme Dark mode values in one declaration
text-wrap: balance / pretty Better headline and paragraph line breaks
Scroll-driven animations (animation-timeline: scroll() / view()) Animations tied to scroll position; support still varies, check MDN
field-sizing: content Auto-growing textareas; support still varies

Saying “I check Baseline status before adopting” is the senior answer.

Q39. CSS-in-JS vs CSS Modules vs utility CSS (Tailwind)? [M]

Approach Pros Cons
Plain CSS / BEM No tooling, fast Global namespace, discipline needed
CSS Modules Locally scoped class names, plain CSS Build step; dynamic styles via variables
Utility-first (Tailwind CSS) Fast to build, consistent design tokens, small final CSS Long class lists, a new vocabulary
Runtime CSS-in-JS (styled-components, Emotion) Co-location, props-based styles Runtime cost, friction with React Server Components
Zero-runtime CSS-in-JS (vanilla-extract, Panda CSS, StyleX) Type-safe, extracted at build time Build tooling

The trend for new React projects has moved toward Tailwind, CSS Modules or zero-runtime solutions, mainly because of server rendering and performance.

6. JavaScript in the Browser and the DOM

Q40. What is the DOM? [J]

The Document Object Model is the browser’s tree representation of the HTML, with an API to read and change it (querySelector, createElement, append, classList, textContent). Changes to the DOM can trigger style recalculation, layout and paint, which is why bulk updates should be batched.

Q41. Explain event bubbling, capturing and delegation. [J]

Events travel down from window to the target (capture), then back up (bubble). Listeners run in the bubble phase by default ({ capture: true } for capture). Delegation means one listener on a parent handles events from many children using event.target.closest(selector); it saves memory and covers elements added later. stopPropagation() stops the event from traveling further; preventDefault() cancels the default action (link navigation, form submission).

Q42. What are passive event listeners? [M]

addEventListener('touchstart', fn, { passive: true }) promises the browser you will not call preventDefault(), so it can scroll immediately without waiting for your handler. Chrome treats touchstart, touchmove and wheel listeners on the window, document and body as passive by default. Use { once: true } for single-use listeners and { signal } with an AbortController to remove many listeners at once.

Q43. innerHTML vs textContent vs innerText? [J]

innerHTML parses a string as HTML, which is an XSS risk with untrusted data. textContent sets or gets raw text and is fast and safe. innerText is layout-aware (respects CSS visibility and line breaks), so reading it can force a layout; prefer textContent.

Q44. What are the observer APIs? [M]

Q45. How do Web Workers and Service Workers differ? [M]

A Web Worker runs JavaScript on a background thread for heavy computation, communicating with postMessage; it cannot touch the DOM. A Service Worker is a programmable network proxy that sits between the page and the network; it intercepts fetch events to serve cached responses (offline support, PWAs), handles push notifications, and lives independently of any single tab. Service Workers require HTTPS.

Q46. What are Web Components? [M]

A set of standards for reusable elements: Custom Elements (customElements.define('my-tabs', class extends HTMLElement {...})), Shadow DOM (encapsulated DOM and styles), and <template>/<slot>. They work in any framework or none. Declarative Shadow DOM (<template shadowrootmode="open">) enables server rendering of shadow roots. Trade-offs: styling across the shadow boundary needs CSS custom properties or ::part, and form participation needs ElementInternals.

Q47. localStorage, sessionStorage, cookies, IndexedDB and the Cache API? [J]

Storage Size (roughly) Lifetime Sent with requests Use for
Cookies About 4 KB each Set by expiry Yes Session IDs (with HttpOnly, Secure, SameSite)
localStorage About 5 MB per origin Until cleared No Small preferences
sessionStorage About 5 MB per origin Tab session No Per-tab draft state
IndexedDB Large, quota-based Until cleared or evicted No Offline data, large structured data
Cache API Quota-based Until cleared No Request/response pairs for Service Workers

localStorage is synchronous and blocks the main thread; avoid it in hot paths and never store secrets there.

Q48. What is CORS? [M]

Browsers block JavaScript from reading responses from another origin (scheme + host + port) unless that server allows it with headers. Simple requests are sent and the browser checks Access-Control-Allow-Origin on the response. Requests with non-simple methods or headers (like PUT or Content-Type: application/json) trigger a preflight OPTIONS request first. Credentials (cookies) need credentials: 'include' on the client and Access-Control-Allow-Credentials: true with an exact origin (not *) on the server. CORS is enforced by browsers; it is not a server-side security control against non-browser clients.

7. How Browsers Work

Q49. What happens when you type a URL and press Enter? [M]

  1. The browser parses the URL and checks its caches (HSTS list, HTTP cache, Service Worker).
  2. DNS resolution finds the IP address.
  3. Connection: TCP + TLS handshake, or QUIC for HTTP/3.
  4. The HTTP request is sent; the server responds (possibly with redirects).
  5. The browser parses HTML into the DOM, discovering CSS, scripts and images (a preload scanner fetches them early).
  6. CSS is parsed into the CSSOM. Render-blocking CSS and synchronous scripts delay rendering.
  7. DOM + CSSOM form the render tree, then layout (geometry), paint (pixels into layers) and composite (layers drawn on the GPU).
  8. JavaScript runs, hydrates or attaches event handlers, and the page becomes interactive.

Tailor the depth to the role; for frontend roles, spend more time on steps 5 to 8.

Q50. What is the critical rendering path? [M]

The steps the browser must finish before the first paint: HTML → DOM, CSS → CSSOM, render tree, layout, paint. CSS is render-blocking and synchronous scripts are parser-blocking. Optimizing it means small, inlined critical CSS, deferring non-critical CSS and scripts, preloading key resources (fonts, the LCP image), and serving HTML fast.

Q51. Reflow (layout) vs repaint vs composite? [M]

Changing geometry (width, top, font size, adding nodes) triggers layout, then paint and composite: the most expensive. Changing only appearance (color, background) triggers paint and composite. Changing transform or opacity on an element with its own layer can skip straight to composite, which runs on the compositor thread and stays smooth even if the main thread is busy. Animate transform and opacity.

Q52. What is layout thrashing? [M]

Interleaving DOM writes and layout reads in a loop (el.style.width = ...; el.offsetHeight; ...) forces the browser to recalculate layout synchronously each time. Fix: batch all reads first, then all writes (or schedule writes in requestAnimationFrame).

Q53. What do the browser’s main thread and compositor thread do? [S]

The main thread runs JavaScript, style, layout and paint recording; if a long task blocks it, input and rendering wait. The compositor thread assembles layers and handles scrolling and transform/opacity animations, so these can stay smooth even when the main thread is busy. Long tasks over 50 ms on the main thread are the root cause of most sluggish interactions.

8. Web Performance and Core Web Vitals

Q54. What are the Core Web Vitals? [J]

Google’s user-centered metrics, measured at the 75th percentile of real page loads:

Metric Measures Good Poor
LCP (Largest Contentful Paint) Loading: when the main content appears ≤ 2.5 s > 4.0 s
INP (Interaction to Next Paint) Responsiveness of all interactions ≤ 200 ms > 500 ms
CLS (Cumulative Layout Shift) Visual stability ≤ 0.1 > 0.25

INP replaced FID (First Input Delay) as a Core Web Vital in March 2024. Other useful metrics: TTFB (server response), FCP (first paint of content), and Total Blocking Time (a lab proxy for INP). Thresholds and definitions are on web.dev/vitals.

Q55. How do you improve LCP? [M]

Find the LCP element first (often a hero image or heading). Then: reduce TTFB (CDN, caching, faster server rendering), make the LCP image discoverable in the HTML (not injected by JavaScript), add fetchpriority="high" to it and do not lazy-load it, serve modern formats (AVIF/WebP) at the right size, remove render-blocking CSS and scripts, and preload critical fonts with font-display: swap or optional.

Q56. How do you improve INP? [M]

Break up long tasks (yield to the main thread with scheduler.yield() where supported or setTimeout), do less work in event handlers (show feedback first, defer the rest), avoid large re-renders (memoization, smaller state updates, virtualization for long lists), reduce third-party scripts, and move heavy computation to a Web Worker. Measure with the Performance panel and real-user data.

Q57. How do you fix CLS? [J]

Set width/height (or aspect-ratio) on images, videos and iframes; reserve space for ads, embeds and late-loading banners; avoid inserting content above existing content unless it is a response to user input; use font-display: optional or size-matched fallback fonts (size-adjust) to reduce font-swap shifts; animate with transform instead of layout properties.

Q58. Lab data vs field data? [M]

Lab data (Lighthouse, WebPageTest, DevTools) comes from a controlled run: reproducible, great for debugging, but not your users’ devices and networks. Field data (RUM) comes from real users: the Chrome UX Report (CrUX), PageSpeed Insights’ field section, or your own collection with the web-vitals library. Core Web Vitals assessment uses field data. A good answer: “I use field data to find problems and lab tools to fix them.”

Q59. How do you reduce JavaScript bundle size? [M]

Measure with a bundle analyzer, then: code-split by route and lazy-load heavy components with dynamic import(), tree-shake (ES modules, sideEffects: false), replace heavy dependencies with lighter ones or native APIs (Intl instead of date libraries for formatting), avoid shipping polyfills to modern browsers, and render static parts on the server so they need no JavaScript.

Q60. What are resource hints? [M]

<link rel="preconnect"> opens a connection to an origin early; dns-prefetch resolves DNS only; preload fetches a resource needed for the current page with high priority (fonts, the LCP image); modulepreload does the same for JS modules; prefetch fetches something likely needed for the next navigation at low priority. The Speculation Rules API (<script type="speculationrules">) can prefetch or prerender whole pages in Chromium browsers. Overusing preload competes with more important resources.

Q61. How do you render a list of 100,000 items? [S]

Do not put them all in the DOM. Use virtualization (windowing): render only the rows in and near the viewport, with spacer elements for the scroll height (TanStack Virtual, react-window). Alternatives: pagination, infinite loading, or content-visibility: auto for long but not huge pages. Mention keeping row heights predictable, and accessibility concerns (find-in-page and screen readers only see rendered rows).

9. Networking, HTTP and Caching

Q62. HTTP/1.1 vs HTTP/2 vs HTTP/3? [M]

HTTP/1.1 handles one request at a time per connection, so browsers open about 6 connections per origin, and old tricks like domain sharding and sprites existed to work around it. HTTP/2 multiplexes many streams over one TCP connection with header compression, but a lost TCP packet stalls every stream (head-of-line blocking). HTTP/3 runs over QUIC (UDP) with streams that are independent at the transport layer, built-in TLS 1.3, faster handshakes and connection migration between networks. With HTTP/2 and later, bundling everything into one huge file matters less, but each request still has a cost.

Q63. How does HTTP caching work? [M]

The standard strategy: hashed static assets cached forever, HTML revalidated.

Q64. What does a CDN do? [J]

Serves content from servers close to the user, cutting latency, offloading the origin, absorbing traffic spikes and attacks, and often terminating TLS and HTTP/3. Many CDNs also run code at the edge (redirects, A/B tests, personalization, server rendering).

Q65. REST vs GraphQL from a frontend point of view? [M]

REST: resource URLs, HTTP caching works naturally, simple tooling, but screens may need several requests (under-fetching) or get more fields than needed (over-fetching). GraphQL: one endpoint, the client asks for exactly the fields it needs, typed schema and great tooling, but HTTP caching is harder (usually POST), it needs a client-side normalized cache (Apollo, urql, Relay) for best results, and servers must guard against expensive queries. tRPC and typed REST (OpenAPI codegen) are popular choices for TypeScript full-stack apps.

Q66. Polling vs long polling vs WebSockets vs Server-Sent Events? [M]

Technique Direction Notes
Polling Client asks every N seconds Simple, wasteful, delayed
Long polling Server holds the request until there is data Works everywhere, more server connections
Server-Sent Events (EventSource) Server to client, over plain HTTP Auto-reconnect, text only; good for feeds, notifications, streaming AI responses
WebSockets Both ways, full duplex Chat, multiplayer, collaborative editing; needs reconnect logic and sticky infrastructure
WebTransport Both ways over HTTP/3 Newer; check browser support

10. Web Security

Q67. What is XSS, and how do you prevent it? [M]

Cross-site scripting: an attacker gets their script to run on your page (stored in the database, reflected from a URL, or created in the DOM). Prevention: let the framework escape output (React, Vue and Angular escape by default), avoid innerHTML, dangerouslySetInnerHTML and v-html with untrusted data or sanitize it with a maintained sanitizer such as DOMPurify, validate URLs (block javascript: links), set a strict Content Security Policy, and keep session cookies HttpOnly so scripts cannot read them. The OWASP XSS Prevention Cheat Sheet is the reference.

Q68. What is CSRF, and how do you prevent it? [M]

Cross-site request forgery: another site makes the user’s browser send an authenticated request (with cookies) to your site. Prevention: SameSite=Lax or Strict cookies (Lax is the default in Chromium-based browsers when the attribute is missing), anti-CSRF tokens for cookie-authenticated forms, checking the Origin header or Fetch Metadata headers (Sec-Fetch-Site) on the server, and never changing state with GET.

Q69. What is a Content Security Policy? [M]

A response header that tells the browser which sources of scripts, styles, images, frames and connections are allowed. A strict nonce-based policy (script-src 'nonce-RANDOM' 'strict-dynamic'; object-src 'none'; base-uri 'none') blocks most injected scripts even if an XSS bug exists. Start with Content-Security-Policy-Report-Only to see what would break. frame-ancestors prevents clickjacking.

Q70. Where should a SPA store auth tokens? [S]

The safest common pattern: keep session state in an HttpOnly, Secure, SameSite cookie set by your own backend (a “backend for frontend”), so JavaScript never sees the token. Tokens in localStorage are readable by any XSS. In-memory tokens are lost on reload and still exposed to XSS while the page runs. For OAuth in browser apps, use the authorization code flow with PKCE; the implicit flow is no longer recommended.

Q71. What other security headers should a frontend engineer know? [M]

Strict-Transport-Security (HTTPS only), X-Content-Type-Options: nosniff, Referrer-Policy, Permissions-Policy (disable camera, geolocation and so on), Cross-Origin-Opener-Policy and Cross-Origin-Embedder-Policy (isolation, needed for SharedArrayBuffer), and frame-ancestors in CSP for clickjacking. Also: Subresource Integrity (integrity attribute) for third-party scripts, and auditing npm dependencies, since supply-chain attacks are now among the top web risks (OWASP Top 10:2025 added “Software Supply Chain Failures” at A03).

11. Frameworks and Rendering Strategies

Q72. Why use a framework instead of plain DOM code? [J]

Frameworks give you declarative UI (describe what the UI should look like for a given state, and the framework updates the DOM), components for reuse, a structured way to manage state, and an ecosystem (routing, data fetching, testing). Plain DOM code is fine for small widgets and can be faster, but at scale, keeping the DOM in sync with state by hand is error-prone.

Q73. Virtual DOM vs fine-grained reactivity vs compilation? [M]

The trend across frameworks has been toward signals and compilers. A TC39 proposal to standardize signals in JavaScript is in early stages.

Q74. Compare React, Vue, Angular and Svelte. [M]

  React Vue Angular Svelte
Type UI library + ecosystem Progressive framework Full framework Compiler-based framework
Templates JSX HTML templates (or JSX) HTML templates HTML-like .svelte files
Reactivity State + re-render (VDOM) Proxy-based refs and reactive Signals and change detection Runes (signals)
Meta-framework Next.js, React Router, TanStack Start Nuxt Angular SSR SvelteKit
Strength Ecosystem, jobs, Server Components Approachable, great docs Batteries included, enterprise structure Little boilerplate, small output

There is no universally best one. A senior answer ties the choice to the team, hiring, existing code and product needs.

Q75. CSR vs SSR vs SSG vs ISR vs streaming? [M]

Strategy HTML produced Good for Watch out for
CSR (client-side rendering) In the browser by JS Dashboards behind login Slow first paint, SEO needs care
SSR (server-side rendering) Per request on the server Personalized, SEO-critical pages Server cost, TTFB
SSG (static generation) At build time Docs, blogs, marketing Rebuilds for changes
ISR (incremental static regeneration) Static, regenerated on a schedule or on demand Large catalogs Stale windows
Streaming SSR Sent in chunks as data resolves Pages with slow data parts Framework support

Q76. What is hydration, and what are islands and resumability? [S]

Hydration is the client re-running component code to attach event handlers and state to server-rendered HTML. It costs JavaScript download and execution, and hydration mismatches happen when server and client render different output (dates, random IDs, window checks). Islands architecture (Astro, Fresh) ships static HTML and hydrates only interactive “islands”. Resumability (Qwik) serializes enough state into the HTML to avoid re-running components at all. React Server Components render some components only on the server, sending no JavaScript for them.

Q77. What is a SPA, and what are its trade-offs? [J]

A single-page application loads one HTML shell and handles navigation in JavaScript with the History API. Pros: app-like transitions, state kept across pages. Cons: large initial bundles, SEO and accessibility work (focus management and announcing route changes), and broken behavior if JS fails. Many teams now use meta-frameworks that mix server rendering with client navigation.

12. State Management and Data Fetching

Q78. What kinds of state exist in a frontend app? [M]

The most common mistake is copying server data into a global store and then fighting to keep it fresh.

Q79. When do you need Redux (or another global store)? [M]

When many distant components read and update the same complex client state, when you need predictable updates with devtools time travel, or when the team benefits from strict conventions. Redux Toolkit removed most of the old boilerplate. For server data, a query cache is usually the better tool, and many apps need little global client state at all.

Q80. What is optimistic UI? [M]

Update the UI immediately as if the server request succeeded, then reconcile when the response arrives, rolling back and showing an error if it fails. Used for likes, toggles and chat messages. React 19’s useOptimistic and TanStack Query’s mutation callbacks support it directly.

Q81. How do you handle race conditions in data fetching? [M]

When a user types fast or switches tabs, older responses can arrive after newer ones and overwrite them. Fixes: cancel stale requests with AbortController, ignore results whose request ID is not the latest, or use a data library that keys requests (TanStack Query, SWR). Debounce search input to send fewer requests.

13. Testing and Tooling

Q82. How do you test frontend code? [M]

Level Tools What to test
Static TypeScript, ESLint, Biome Type errors, suspicious patterns
Unit Vitest, Jest Pure functions, hooks, stores
Component / integration Testing Library with Vitest or Jest; Storybook interaction tests Components the way a user uses them: by role and label, not by class names
End-to-end Playwright, Cypress Critical flows in real browsers
Visual regression Playwright screenshots, Chromatic Unintended visual changes
Accessibility axe-core in tests Automated a11y checks

Mock the network at the boundary (Mock Service Worker) rather than mocking your own modules.

Q83. What do bundlers and build tools do? [J]

They resolve imports, transform code (TypeScript, JSX, modern syntax), bundle and split it into chunks, tree-shake, minify, fingerprint file names for caching, and run a dev server with hot module replacement. Vite is the most common choice for new non-framework projects (fast native-ESM dev server, Rollup-compatible production builds, and a Rust-based bundler, Rolldown, in recent versions); webpack is still common in older apps; frameworks like Next.js ship their own (Turbopack). esbuild, SWC and Oxc are fast Rust/Go-based compilers used underneath many tools.

Q84. What does TypeScript give a frontend team? [J]

Type checking catches bugs before runtime, editors give better autocomplete and refactoring, and types document component props and API responses. Types are erased at runtime, so validate external data (API responses, form input) with a runtime schema library such as Zod or Valibot. See typescript-cheatsheet.

Q85. How do you structure a large frontend codebase? [S]

Group by feature (features/checkout/) rather than by file type, keep shared UI in a design system package, enforce boundaries (lint rules on imports), use a monorepo tool (pnpm workspaces, Turborepo, Nx) when several apps share code, and consider micro-frontends only when independent teams truly need independent deploys, because they add runtime and consistency costs.

14. Frontend System Design

Frontend system design asks you to design a product’s client architecture, not the backend’s databases. A useful framework (sometimes called RADIO: Requirements, Architecture, Data model, Interface, Optimizations):

  1. Requirements: core features, users and devices, scale, offline needs, SEO, accessibility, internationalization. Ask before designing.
  2. Architecture: components and how they talk (view, controller/store, server cache, API client). Rendering strategy (CSR/SSR/SSG).
  3. Data model: client-side entities and where each piece of state lives (server cache vs local vs URL).
  4. Interface (API): endpoints or GraphQL queries the client needs, pagination style, real-time channel.
  5. Optimizations: performance, accessibility, error and loading states, security, i18n, observability.

Q86. Design a news feed (like a social media timeline). [S]

Q87. Design an autocomplete (typeahead) component. [S]

Q88. Other common frontend system design prompts

Prompt Key topics to cover
Chat / messaging app WebSockets, message ordering, optimistic send, offline queue, read receipts, virtualization of history
Photo gallery / Pinterest-style grid Masonry layout, responsive images, lazy loading, virtualization
Collaborative editor (Google Docs-like) Operational transforms vs CRDTs, presence, conflict resolution, offline
E-commerce product page SSR/ISR for SEO, LCP image, cart state, A/B tests, analytics
Video streaming UI Adaptive bitrate (HLS/DASH), preloading, controls accessibility
Design system / component library Tokens, theming, accessibility, versioning, documentation, tree-shaking
Dashboard with live data Polling vs push, chart performance, data windowing, error states

15. Coding and UI Exercises

Practice building each of these with plain HTML, CSS and JavaScript first, then in your framework. Aim for working, accessible and readable within 45 minutes.

Exercise What it tests
Accordion Semantics (<details>/<summary> or buttons with aria-expanded), keyboard
Tabs ARIA tabs pattern, roving tabindex, arrow keys
Modal dialog <dialog>, focus trap and return, Escape, scroll locking
Autocomplete Debounce, async race conditions, combobox ARIA
Star rating Radio group semantics, hover vs selected states
Infinite scroll list IntersectionObserver, loading and error states
Image carousel Timers, pause on hover and focus, reduced motion, controls
Todo list with filters State management, URL state, persistence
Data table with sort and pagination Derived state, aria-sort, performance
Progress bar / countdown timer Timers, requestAnimationFrame, cleanup
Nested file explorer (tree view) Recursion, tree ARIA pattern
Implement getElementsByClassName or querySelectorAll-like traversal DOM tree traversal (DFS/BFS)

JavaScript utilities that frontend interviews ask for (debounce, throttle, Promise.all, deep clone, event emitter, classnames-style helpers) are implemented and tested in javascript-interview-questions.

LeetCode problems with a frontend flavor:

Problem Why
2627. Debounce Timers and closures
2694. Event Emitter Pub/sub, common in UI code
2625. Flatten Deeply Nested Array Recursion on nested data
102. Binary Tree Level Order Traversal BFS, like walking the DOM
146. LRU Cache Client-side caches
20. Valid Parentheses Stack; similar to matching HTML tags

Best Resources to Prepare

Resource Type Cost Best for
MDN Web Docs Docs Free Best reference for HTML, CSS, DOM and Web APIs, with compatibility tables
web.dev Learn Courses Free Best free courses: Learn HTML, CSS, Accessibility, Performance, Images, Forms
web.dev Core Web Vitals Guides Free Metric definitions and optimization guides
Baseline and Can I use Support data Free Checking whether a feature is safe to use
WCAG 2.2 and WAI-ARIA Authoring Practices Guide Standards, patterns Free Accessibility rules and correct widget patterns
Front End Interview Handbook Guide Free Overview of frontend interview formats and question types
h5bp Front-end Developer Interview Questions Question list Free Long list of questions (without answers) to self-test
Chrome DevTools docs Docs Free Performance, network and memory debugging
OWASP Cheat Sheet Series Security guides Free XSS, CSRF, CSP, session management
javascript.info Tutorial Free JavaScript and browser APIs in depth
BFE.dev Practice Free tier JavaScript and UI coding questions
GreatFrontEnd Practice Free tier, most content paid UI coding and frontend system design questions with solutions
Josh W. Comeau’s CSS for JavaScript Developers Course Paid Deep understanding of CSS layout

If you pick only two: web.dev Learn for structured study and MDN as your reference while building the exercises in section 15.

FAQ

What are the most common frontend interview questions? Semantic HTML and accessibility basics, the box model and specificity, Flexbox vs Grid, centering, event delegation, this and closures, the event loop, what happens when you type a URL, Core Web Vitals, caching, CORS, XSS and CSRF, and how your framework renders and updates the UI.

Do frontend interviews include LeetCode? Often, but usually easier problems than backend roles, and many companies replace them with UI coding or JavaScript utility questions. Arrays, strings, hash maps, and tree traversal (because the DOM is a tree) are the most useful topics.

How is frontend system design different from backend system design? It focuses on the client: component architecture, state and data flow, rendering strategy, API shape from the client’s point of view, performance, accessibility, offline support and real-time updates. Databases, sharding and queues only come up in passing.

Should I prepare in plain JavaScript or my framework? Both. Many UI rounds let you choose; plain DOM code shows you understand the platform, while your framework shows productivity. Know at least one framework deeply.

How much CSS do I need for a frontend interview? Enough to build responsive layouts from scratch with Flexbox and Grid, explain specificity, stacking contexts and the box model, and make components accessible and themeable. Senior roles add architecture (design tokens, cascade layers, scaling CSS across teams).

Do I need to know accessibility? Yes. It is increasingly part of every frontend loop and a legal requirement for many products. Know semantic HTML, keyboard support, focus management, labels, contrast and when to use ARIA.

Where to Go Next

Contributing

Pull requests are welcome: new questions, clearer answers, corrections when browser support changes, and new UI exercises. Please keep answers short and in your own words, mark the level ([J], [M], [S]), and link a primary source (MDN, web.dev, W3C, WHATWG) for claims about browser behavior or support.

License

Content is licensed under CC BY 4.0.

If this helped you, a star helps others find it.

More free resources

Part of the Ralpberry Labs open-source collection. See also Top 100 Open Source.