Frontend Developer Interview Questions and Answers
Last updated 2026-11-19
Frontend interviews test three layers: the platform (HTML, CSS, JavaScript and the browser), a framework on top, and the judgement to ship fast, accessible interfaces. This page covers the platform layer and the practical questions that come up whichever framework you use. For React-specific depth, see the separate React banks linked below.
The answers are written the way you would say them in an interview: a direct statement first, then the reason, then a caveat or example. Each includes only claims that hold for current browsers and tooling.
| Core topics | JavaScript, CSS layout, browser rendering, accessibility, performance |
|---|---|
| Usual formats | Machine-coding round, JavaScript questions, UI build, system design for UIs |
| Questions here | 18 |
What the machine-coding round looks for
Many companies give 60 to 90 minutes to build a small widget such as a typeahead, a star rating, a modal or a todo list with no libraries. They watch structure, naming, keyboard support, handling of empty and error states, and whether the component stays correct after rapid interaction. Practise building three or four of these end to end with plain HTML, CSS and JavaScript or React.
Preparation checklist
- Be able to explain the event loop with a microtask versus macrotask example.
- Know flexbox and grid well enough to build a layout without looking anything up.
- Learn the three Core Web Vitals: LCP, INP and CLS, and one fix for each.
- Use a screen reader or at least the keyboard alone on a page you built.
- Read the guide on how to crack a frontend interview for the round structure.
Frontend Developer Interview Questions and Answers: questions with worked answers
1 Explain the CSS box model.
easyEvery element is a box made of content, padding, border and margin, from the inside out. By default, width sets the content box only, so padding and border add to the rendered size. Setting box-sizing: border-box makes width include padding and border, which is why most resets apply it globally. Vertical margins of adjacent block elements can collapse into one, but padding and borders never do.
2 How is CSS specificity calculated?
easySpecificity compares four tiers in order: inline style, then IDs, then classes, attributes and pseudo-classes, then elements and pseudo-elements. A higher tier always beats any number of lower ones, so one ID outranks ten classes. Equal specificity falls back to source order. The universal selector adds nothing, and !important overrides normal declarations. Cascade layers with @layer now let you control order explicitly before specificity is considered.
3 What is semantic HTML and why does it matter?
easySemantic elements such as header, nav, main, article, button and label describe meaning, not appearance. Browsers and assistive technology use that meaning: a button is focusable, activated by Enter and Space and announced as a button, while a div with a click handler gives none of that. Semantic markup also helps search engines and keeps CSS simpler. Use ARIA only when no native element fits.
4 What is the difference between == and === in JavaScript?
easy=== compares value and type with no conversion. == converts operands first using coercion rules, which gives surprises such as 0 == "" being true and null == undefined being true. Use === by default. The one common deliberate use of == is value == null to test for both null and undefined at once. See JavaScript interview questions for coercion in depth.
5 Explain event delegation.
mediumInstead of attaching a listener to every child, attach one to a common ancestor and use event bubbling to catch events from descendants, identifying the source with event.target or closest(). It saves memory and works for elements added later. Not all events bubble: focus and blur do not, though focusin and focusout do. Use stopPropagation sparingly because it breaks delegation higher up.
javascriptlist.addEventListener('click', (e) => { const item = e.target.closest('li[data-id]'); if (!item || !list.contains(item)) return; select(item.dataset.id); });6 Write a debounce function and explain when to use it.
mediumDebounce delays calling a function until a quiet period has passed since the last call. Use it for search-as-you-type or window resize handling where only the final value matters. Throttle is different: it allows at most one call per interval, which suits scroll handlers. The returned function must keep the latest arguments and this value, and clear the previous timer on each call.
javascriptfunction debounce(fn, wait) { let t; return function (...args) { clearTimeout(t); t = setTimeout(() => fn.apply(this, args), wait); }; }7 Explain the JavaScript event loop with microtasks and macrotasks.
mediumJavaScript runs one call stack. When it empties, the event loop runs all queued microtasks, which are promise callbacks and queueMicrotask, then renders if needed, then takes the next macrotask such as a setTimeout callback or a click handler. So promise callbacks always run before timers. The output of the snippet is 1, 4, 3, 2.
javascriptconsole.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4);8 Flexbox or grid: how do you choose?
mediumFlexbox lays out in one dimension, a row or a column, and is best for aligning items in a toolbar, a nav or a card footer. Grid lays out in two dimensions at once and suits page layouts and galleries. Grid lets you define tracks first and place content into them, while flex sizes from content. They combine well: a grid for the page, flex inside each cell. Use gap in both instead of margins.
css.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: 1rem; }9 Compare cookies, localStorage and sessionStorage.
mediumCookies are sent with every matching request, can be HttpOnly so scripts cannot read them, and hold about 4 KB each. localStorage keeps around 5 MB per origin, persists until cleared, is synchronous and readable by any script on the page, so an XSS bug exposes it. sessionStorage is the same API but scoped to one tab and cleared when the tab closes. Store session tokens in HttpOnly, Secure, SameSite cookies, not in localStorage.
10 What is CORS and why does a request fail with a CORS error?
mediumBrowsers block a page from reading responses of another origin unless that server opts in with Access-Control-Allow-Origin. For non-simple requests, such as JSON POSTs with custom headers, the browser first sends an OPTIONS preflight, and the server must answer with allowed methods and headers. The fix is on the server, not the client. A wildcard origin cannot be combined with credentials. CORS protects users, not the server, and curl ignores it.
11 What are the Core Web Vitals and how do you improve each?
mediumLargest Contentful Paint measures loading, with a good value of 2.5 seconds or less. Improve it by optimising the hero image, preloading it and cutting render-blocking CSS. Interaction to Next Paint, good at 200 ms or less, replaced First Input Delay in 2024. Improve it by breaking up long tasks and reducing JavaScript. Cumulative Layout Shift, good at 0.1 or less, is fixed by reserving space with width, height or aspect-ratio. See web performance interview questions.
12 How do you make a custom dropdown accessible?
mediumPrefer a native select or button plus listbox pattern. If you build your own, use a button with aria-haspopup and aria-expanded, a list with role=listbox and options with role=option, manage aria-activedescendant, support Arrow keys, Home, End, Enter, Escape and type-ahead, and return focus to the button on close. Ensure visible focus styles and 4.5:1 text contrast. Test with a keyboard only and a screen reader.
13 What is the difference between async/await and promises?
mediumasync/await is syntax over promises. An async function always returns a promise, and await pauses that function, not the thread, until the promise settles, using try/catch for rejections. Independent calls should start together with Promise.all, because awaiting them one after another serialises them. Promise.allSettled waits for all outcomes without short-circuiting on the first rejection.
javascriptconst [user, posts] = await Promise.all([ fetch('/api/user').then(r => r.json()), fetch('/api/posts').then(r => r.json()), ]);14 How do closures work and where do they bite?
mediumA closure is a function plus the variables of the scope where it was created, kept alive after that scope returns. They power callbacks, memoisation and private state. The classic trap is var in a loop: all callbacks share one binding, while let creates a new binding per iteration. Closures can also retain large objects longer than expected and cause memory leaks. See JavaScript closures interview questions.
15 Describe how the browser renders a page and what causes layout thrashing.
hardThe browser parses HTML into the DOM, CSS into the CSSOM, combines them into a render tree, computes layout, paints and composites layers. Layout thrashing happens when you interleave DOM writes with reads of layout properties such as offsetHeight, forcing a synchronous reflow each time. Batch reads first, then writes, or use requestAnimationFrame. Animating transform and opacity avoids layout and paint and can run on the compositor.
16 How would you design a typeahead component?
hardDebounce input by about 200 ms, cancel stale requests with AbortController so slow responses cannot overwrite newer ones, cache results by query, and show loading, empty and error states. Use the combobox ARIA pattern with keyboard navigation. Highlight matches safely without innerHTML on raw text. For very large lists, virtualise rendering. Mention that the server should also rate limit and the client should trim and ignore empty queries.
17 What is XSS and how do you prevent it in a frontend app?
hardCross-site scripting runs attacker script in your page, usually from untrusted data placed into HTML. Prevent it by letting the framework escape output, avoiding innerHTML and dangerouslySetInnerHTML with raw data, sanitising unavoidable HTML with a library like DOMPurify, setting a strict Content Security Policy, and keeping tokens in HttpOnly cookies. Validate URLs so javascript: links are rejected. See web security and OWASP interview questions.
18 How do you reduce JavaScript bundle size?
hardFirst measure with a bundle analyser. Then split code by route with dynamic import(), drop unused code through tree shaking by using ES modules, replace heavy libraries with lighter ones such as date-fns functions for a full date library, lazy load below-the-fold components, compress with Brotli, and cache hashed files for a long time. Avoid shipping polyfills modern browsers do not need.
Frequently asked questions
What is asked in a frontend developer interview?
JavaScript fundamentals, CSS layout, browser behaviour, a framework such as React, accessibility, performance and usually a machine-coding round where you build a small UI.
Do I need to know a framework for frontend interviews?
Most roles expect one, commonly React, Angular or Vue. Platform knowledge still decides many rounds, because frameworks come and go while HTML, CSS and JavaScript remain.
How do I prepare for a machine-coding round?
Build small components such as a modal, tabs, autocomplete and a paginated table in under an hour each, and handle keyboard use, empty states and errors from the start.
Are Core Web Vitals asked in interviews?
Yes, increasingly. Know LCP, INP and CLS, their good thresholds, and one practical fix for each.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Full Stack Developer Interview Questions and Answers
- Generative AI and LLM Interview Questions and Answers
- Google Cloud (GCP) Interview Questions and Answers
- GraphQL Interview Questions and Answers
- Hibernate and JPA Interview Questions and Answers
- HTML and CSS Interview Questions and Answers
- iOS and Swift Interview Questions and Answers
- Jenkins and CI/CD Interview Questions and Answers
- Kubernetes Interview Questions and Answers
- Machine Learning Interview Questions and Answers
- Manual Testing Interview Questions and Answers
- MERN Stack Interview Questions and Answers