Skip to content

Frontend Developer Interview Questions & Answers

40 questions for Frontend Developer interviews — 27 easy, 13 medium.

About the Frontend Developer role

A frontend developer builds responsive, accessible user interfaces from designs and connects them to APIs. They write modern JavaScript or TypeScript, style components with scalable CSS, handle loading and error states, and fix cross-browser bugs. Freshers with strong JavaScript fundamentals and two or three solid projects can enter this role at product companies, startups and IT services firms.

Modern JavaScript Responsive CSS API integration Accessibility basics Git
Solved for this roleStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

Explain optional chaining and the nullish coalescing operator.

Save to ▾
Show answer
Optional chaining ?. stops evaluation and returns undefined if the value before it is null or undefined, so user?.address?.pincode never throws. Nullish coalescing ?? returns the right side only when the left is null or undefined, unlike || which also replaces 0, false and empty strings. For example, const qty = input ?? 1 keeps a valid 0, while input || 1 would wrongly change 0 into 1.
02

A new browser API you used does not work in older Safari versions. How do you handle it?

Save to ▾
Show answer
I would use feature detection, such as if ('share' in navigator), rather than browser sniffing, and provide a fallback like a copy-link button. Checking Can I Use and the project's browser support list before building avoids surprises. Where reasonable, a small polyfill can fill gaps. This progressive enhancement approach ensures the core feature works everywhere while newer browsers get a better experience.
03

Compare IntersectionObserver, ResizeObserver and MutationObserver.

Save to ▾
Show answer
IntersectionObserver reports when an element enters or leaves the viewport or a container, used for lazy loading, infinite scroll and analytics impressions. ResizeObserver reports changes to an element's size, useful for charts that must redraw when their container changes. MutationObserver reports DOM changes like added nodes or changed attributes. All three are asynchronous and far more efficient than polling or scroll and resize listeners.
04

Your app must now support an Arabic right-to-left version. What changes are needed in CSS?

Save to ▾
Show answer
I would set dir='rtl' on the html element for that locale and replace physical properties like margin-left, padding-right and left with logical ones such as margin-inline-start and inset-inline-start. Flexbox and Grid follow direction automatically. Directional icons like arrows need flipping with a transform in RTL, while logos and media do not. I would test layouts with real Arabic text, which has different line heights.
05

Cancel an older search request when the user types again using AbortController.

Save to ▾
Show answer
Keep a controller per request and abort the previous one: let controller; async function search(term) { controller?.abort(); controller = new AbortController(); try { const res = await fetch('/api/search?q=' + encodeURIComponent(term), { signal: controller.signal }); renderResults(await res.json()); } catch (err) { if (err.name !== 'AbortError') showError(err); } } This prevents slow old responses from overwriting newer results.
06

Flatten a deeply nested array without using Array.prototype.flat.

Save to ▾
Show answer
A recursive reduce handles any depth: function flatten(arr) { return arr.reduce((acc, item) => Array.isArray(item) ? acc.concat(flatten(item)) : acc.concat(item), []); } flatten([1, [2, [3, [4]], 5]]); // [1, 2, 3, 4, 5] In real code, arr.flat(Infinity) does the same. For extremely deep nesting, an iterative version with a stack avoids call stack overflow.
07

Editing one item in a copied list also changes the original list. Why?

Save to ▾
Show answer
Copying an array with spread or slice creates a new array, but the objects inside are still the same references. Changing copy[0].qty changes the original object too. The fix is to create new objects for changed items, for example list.map(item => item.id === id ? { ...item, qty: item.qty + 1 } : item), or use structuredClone when a full deep copy is genuinely needed.
08

A full-screen hero section is cut off at the bottom on mobile phones. How do you fix it?

Save to ▾
Show answer
The section uses height: 100vh, which on mobile includes the area hidden behind the browser's address bar. I would change it to min-height: 100svh or 100dvh so the height matches the visible viewport, keeping 100vh as a fallback line before it for very old browsers. Using min-height instead of height also lets content grow on small screens instead of overflowing.
09

How does Tailwind CSS keep the final CSS file small?

Save to ▾
Show answer
Tailwind scans your source files for class names and generates only the utilities you actually use, so the production CSS is usually a few kilobytes even though thousands of utilities are available. This requires class names to appear as complete strings in the code. Tailwind v4 uses a CSS-first configuration with @theme for design tokens and detects source files automatically.
10

How can you communicate between multiple tabs of the same site?

Save to ▾
Show answer
BroadcastChannel lets same-origin tabs, windows and workers publish and subscribe to messages on a named channel, which suits syncing logout, theme or cart updates. The storage event fires in other tabs when localStorage changes, which is a simple fallback. SharedWorker can hold shared state for all tabs. Each option works only within the same origin, so cross-domain sync needs a server or postMessage.
11

Explain dependencies, devDependencies and peerDependencies.

Save to ▾
Show answer
dependencies are packages needed at runtime, such as a charting library. devDependencies are used only during development and build, like Vite, ESLint, TypeScript and test runners. peerDependencies are declared by libraries that expect the host project to provide a package, for example a React component library listing react as a peer, which avoids shipping two copies. For bundled frontend apps, the split mainly documents intent and affects installs.
12

Where do you see yourself in five years as a frontend developer?

Save to ▾
Show answer
In five years, I want to be a senior frontend engineer who owns complex features end to end and helps shape architecture decisions. I plan to deepen my skills in performance, accessibility and TypeScript, and contribute to a design system. I also want to mentor juniors, because teaching others is how I learned best. I hope to grow within a team where I can take on that responsibility.
13

What are pure functions and why does immutability matter in frontend code?

Save to ▾
Show answer
A pure function returns the same output for the same input and has no side effects such as changing external variables. Immutability means creating new objects instead of modifying existing ones, for example using spread syntax to update state. Together they make code predictable and easy to test, and they let frameworks detect changes with a simple reference comparison, which enables efficient re-rendering.
14

Keep product filters in sync with the URL query string.

Save to ▾
Show answer
Read params on load and update them without reload: const params = new URLSearchParams(location.search); const category = params.get('category') ?? 'all'; applyFilters({ category }); function updateFilter(key, value) { const p = new URLSearchParams(location.search); value ? p.set(key, value) : p.delete(key); history.pushState(null, '', '?' + p.toString()); applyFilters(Object.fromEntries(p)); } window.addEventListener('popstate', () => applyFilters(Object.fromEntries(new URLSearchParams(location.search)))); Users can now share and bookmark filtered views.
15

At a high level, how does React's virtual DOM and reconciliation work?

Save to ▾
Show answer
React components return a description of the UI as a tree of elements. When state changes, React renders a new tree and compares it with the previous one, a process called reconciliation, then applies only the minimal DOM changes needed. Keys help it match list items correctly. The React Compiler now adds automatic memoisation, reducing unnecessary re-renders without manual useMemo calls.
16

What are higher-order functions and currying?

Save to ▾
Show answer
A higher-order function takes a function as an argument or returns one, like map, filter or a custom withLogging(fn) wrapper. Currying transforms a function with many arguments into a chain of single-argument functions, so add(2)(3) returns 5. Currying makes partial application easy, for example creating formatINR = formatCurrency('INR') once and reusing it. Overusing it can reduce readability for teams unfamiliar with functional style.
17

Move a heavy calculation into a Web Worker.

Save to ▾
Show answer
The worker runs on its own thread and talks through messages: // worker.js self.onmessage = (e) => { const total = e.data.reduce((sum, row) => sum + row.amount, 0); self.postMessage(total); }; // main.js const worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); worker.postMessage(bigArrayOfRows); worker.onmessage = (e) => showTotal(e.data); The UI stays responsive. Data is copied between threads, so for huge binary data use transferable objects like ArrayBuffer.
18

Compare Promise.all, Promise.allSettled, Promise.race and Promise.any.

Save to ▾
Show answer
Promise.all resolves with all results when every promise succeeds, but rejects immediately if any fails. Promise.allSettled always waits for all and returns each outcome with status fulfilled or rejected, useful for dashboards loading independent widgets. Promise.race settles with the first promise to settle, often used for timeouts. Promise.any resolves with the first success and rejects only if all fail, useful for trying multiple mirrors.
19

Search results sometimes show data for an older query. What is happening?

Save to ▾
Show answer
This is a race condition: requests for 'ja' and 'java' are in flight together, and if the older one responds last, it overwrites the newer results. I would cancel the previous request with AbortController, or tag each request with an id and ignore responses that are not the latest. Debouncing the input reduces the number of requests, and caching repeated queries makes responses faster and more consistent.
20

Tell me about a time you automated a repetitive task.

Save to ▾
Show answer
Situation: in my internship, we resized and compressed product images manually before every upload. Task: I wanted to save the team time. Action: I wrote a small Node script using Sharp that converted images to WebP in three sizes and added it as an npm script. Result: a task that took an hour per batch became a one-minute command, and image sizes dropped by more than half.
21

Implement a throttle function.

Save to ▾
Show answer
Throttle allows a function to run at most once in a given interval: function throttle(fn, wait) { let last = 0; return function (...args) { const now = Date.now(); if (now - last >= wait) { last = now; fn.apply(this, args); } }; } window.addEventListener('scroll', throttle(updateProgressBar, 100)); Unlike debounce, which waits for calls to stop, throttle fires regularly during continuous events such as scrolling or dragging.
22

Predict the output order of synchronous code, promises and setTimeout.

Save to ▾
Show answer
Synchronous code runs first, then microtasks, then macrotasks: console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); queueMicrotask(() => console.log('D')); console.log('E'); // Output: A, E, C, D, B A and E are synchronous. C and D are microtasks queued in order. B is a macrotask and waits until the microtask queue is empty, even with a 0 ms delay.
23

How does destructuring with default values work?

Save to ▾
Show answer
Destructuring pulls values out of arrays or objects into variables. Defaults apply only when the value is undefined, not when it is null. For example, const { name, city = 'Delhi' } = user sets city to Delhi if the property is missing. Function parameters can be destructured too, like function render({ title, size = 'md' } = {}), which avoids errors when no argument is passed and documents expected options clearly.
24

What is a JavaScript bundler and why do frontend projects need one?

Save to ▾
Show answer
A bundler takes your source files, follows imports to build a dependency graph and outputs optimised files for the browser. Along the way it transpiles TypeScript and JSX, processes CSS, handles images, minifies code, removes unused exports and adds content hashes for caching. Native ES modules work in browsers, but loading hundreds of unoptimised files is slow, so production builds still use bundlers like Vite, webpack or Rspack.
25

Show clear focus styles only for keyboard users.

Save to ▾
Show answer
:focus-visible applies when the browser decides focus should be shown, typically for keyboard navigation: button:focus-visible, a:focus-visible { outline: 3px solid #2563eb; outline-offset: 2px; } button:focus:not(:focus-visible) { outline: none; } Mouse users do not see an outline on click, while keyboard users always know where they are. Never remove outlines globally with *:focus { outline: none } without a replacement.
26

Define brand design tokens in Tailwind CSS v4.

Save to ▾
Show answer
Tokens go in CSS with the @theme directive: @import 'tailwindcss'; @theme { --color-brand-500: #2563eb; --color-brand-700: #1d4ed8; --font-display: 'Poppins', sans-serif; --radius-card: 12px; } /* usage in markup */ /* <button class='bg-brand-500 hover:bg-brand-700 rounded-card font-display'> */ Tailwind generates utilities like bg-brand-500 from these variables and also exposes them as CSS custom properties for use in plain CSS.
27

What is the difference between ES modules and CommonJS?

Save to ▾
Show answer
ES modules use import and export, are statically analysable, load asynchronously and are the standard in browsers and modern Node. CommonJS uses require and module.exports, loads synchronously and was Node's original system. Because ES module imports are static, bundlers can tree-shake unused exports, which shrinks bundles. Mixing the two causes interop issues, so new frontend projects use ES modules with type: module in package.json.
28

How do you handle a designer who expects pixel-perfect matching on every device?

Save to ▾
Show answer
Situation: a designer flagged small spacing differences between Figma and my build on several phones. Task: I needed to address concerns while keeping the layout fluid. Action: I fixed genuine mistakes immediately, then showed how fixed pixel values would break on other screens and proposed shared spacing tokens. Result: we agreed on tokens and breakpoints, and future handoffs had far fewer revision rounds.
29

Write a visually-hidden utility class for screen-reader-only text.

Save to ▾
Show answer
This hides content visually but keeps it readable by assistive technology: .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } Use it for labels on icon-only buttons, such as <button><svg aria-hidden='true'></svg><span class='sr-only'>Close</span></button>. display: none would hide the text from screen readers too.
30

How do browser permission APIs like Geolocation and Notifications work?

Save to ▾
Show answer
Powerful features require user consent, a secure HTTPS context and usually a user gesture. Calling navigator.geolocation.getCurrentPosition or Notification.requestPermission shows a browser prompt; if the user denies it, you cannot ask again easily. navigator.permissions.query lets you check the current state first. Good UX explains why you need the permission before triggering the prompt, for example asking for location only when the user taps 'Find nearest centre'.
31

An accordion animation stutters on low-end Android phones. What is wrong?

Save to ▾
Show answer
Most likely it animates height, max-height or margin, which forces layout recalculation every frame. I would check the Performance panel for long layout events. Fixes include animating transform and opacity, using the newer interpolate-size or calc-size features for height where supported, or animating grid-template-rows from 0fr to 1fr, which is cheaper. Testing with CPU throttling in DevTools reveals these issues before users do.
32

What is a Progressive Web App?

Save to ▾
Show answer
A Progressive Web App is a website that behaves like an installable app. It needs HTTPS, a web app manifest with name, icons and theme colour, and usually a service worker for offline support and caching. Users can add it to their home screen and it opens in a standalone window. PWAs are popular in India for lightweight apps that work on low-end phones and patchy mobile networks.
33

How does client-side rendering affect SEO and social sharing?

Save to ▾
Show answer
With pure client-side rendering, the initial HTML is mostly empty and content appears after JavaScript runs. Google can render JavaScript, but it happens later and less reliably, while many social media link previewers and some search engines do not run JavaScript at all, so titles and images are missing. Server rendering or prerendering important pages ensures content and meta tags are in the initial HTML.
34

Why use requestAnimationFrame instead of setTimeout for animations?

Save to ▾
Show answer
requestAnimationFrame runs your callback right before the browser paints the next frame, usually 60 or 120 times per second matching the display. It pauses in background tabs, saving battery, and avoids the drift and dropped frames that setTimeout causes because timers are not synced with rendering. The callback receives a high-precision timestamp, so animations can be calculated from elapsed time rather than fixed steps.
35

Implement a copy-to-clipboard button with user feedback.

Save to ▾
Show answer
The async Clipboard API works in secure contexts after a user action: copyBtn.addEventListener('click', async () => { try { await navigator.clipboard.writeText(couponCode.textContent); copyBtn.textContent = 'Copied!'; } catch { copyBtn.textContent = 'Press Ctrl+C to copy'; } setTimeout(() => (copyBtn.textContent = 'Copy code'), 2000); }); An aria-live region can announce 'Copied' to screen reader users, since a changing button label may not always be read out.
36

How does the History API enable client-side routing?

Save to ▾
Show answer
history.pushState(state, '', '/courses/react') changes the URL and adds a history entry without reloading the page, and replaceState updates the current entry. When users press back or forward, the popstate event fires and the app renders the matching view. The server must return the app's HTML for all routes, otherwise refreshing a deep link gives a 404. Routers in SPA frameworks are built on this API.
37

Why are dvh and svh units better than vh on mobile?

Save to ▾
Show answer
On mobile browsers, 100vh equals the height with the address bar hidden, so a full-screen section gets cut off when the bar is visible. svh is the small viewport height with browser UI shown, lvh the large one, and dvh updates dynamically as the bar appears or hides. Using min-height: 100dvh for hero sections or app shells prevents content hiding behind browser chrome.
38

Why do you want to build a career in frontend development?

Save to ▾
Show answer
I like work where users see the result directly. In college I built a timetable app for my class, and watching classmates use it daily taught me how small UI details matter. Frontend combines logic, design and performance, and the ecosystem keeps evolving, which keeps me learning. I want to build fast, accessible interfaces for products used by millions of people across India.
39

Why does await inside forEach not wait for each item?

Save to ▾
Show answer
forEach ignores the promise returned by an async callback, so all callbacks start almost at once and forEach finishes before any await completes. Code after it runs too early. For sequential processing, use a for...of loop with await inside. For parallel processing with a final result, use await Promise.all(items.map(async item => ...)). Choosing between them depends on whether order and rate limits matter.
40

What colour contrast ratios does WCAG require?

Save to ▾
Show answer
WCAG 2.2 level AA requires a contrast ratio of at least 4.5 to 1 for normal text and 3 to 1 for large text, which is about 24 pixels regular or 19 pixels bold. Interface components and focus indicators need 3 to 1 against adjacent colours. Level AAA raises text to 7 to 1. Tools like the DevTools contrast checker help catch light grey text that fails these limits.

Frequently asked questions

What does a Frontend Developer do?

A frontend developer builds responsive, accessible user interfaces from designs and connects them to APIs. They write modern JavaScript or TypeScript, style components with scalable CSS, handle loading and error states, and fix cross-browser bugs. Freshers with strong JavaScript fundamentals and two or three solid projects can enter this role at product companies, startups and IT services firms.

Which skills are tested in a Frontend Developer interview?

Expect questions on Modern JavaScript, Responsive CSS, API integration, Accessibility basics, Git. Most rounds also ask you to explain a project and solve one practical problem live.

How do I prepare for a Frontend Developer interview?

Revise Modern JavaScript, CSS Architecture and Accessibility, Browser APIs first using the topic sheets, practise the questions on this page aloud, then do one full mock interview to practise timing.