Skip to content

Practical Frontend Development Interview Questions

45 questions with answers. Hands-on questions where you write code, a query, a formula or concrete steps.

How to approach these questions

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.

Solved — practicalStart 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

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.
02

Write a polyfill for Promise.all.

Save to ▾
Show answer
Resolve when all succeed, keep result order, reject on first failure: function promiseAll(items) { return new Promise((resolve, reject) => { const results = []; let done = 0; if (items.length === 0) return resolve(results); items.forEach((item, i) => { Promise.resolve(item).then(value => { results[i] = value; if (++done === items.length) resolve(results); }, reject); }); }); } Promise.resolve handles plain values mixed with promises.
03

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.
04

Write a fetch wrapper that retries with exponential backoff.

Save to ▾
Show answer
Retry on network errors and 5xx responses, doubling the delay each time: async function fetchWithRetry(url, options = {}, retries = 3, delay = 500) { try { const res = await fetch(url, options); if (res.status >= 500 && retries > 0) throw new Error('Server ' + res.status); return res; } catch (err) { if (retries === 0) throw err; await new Promise(r => setTimeout(r, delay)); return fetchWithRetry(url, options, retries - 1, delay * 2); } } Do not retry 4xx errors, and only retry idempotent requests.
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

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.
07

Write a type-safe getProperty function using generics and keyof.

Save to ▾
Show answer
Constrain the key to the object's own keys: function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; } const course = { title: 'Frontend', weeks: 14 }; const weeks = getProperty(course, 'weeks'); // number // getProperty(course, 'price'); // compile error T[K] is an indexed access type, so the return type matches the chosen property. Typos in key names are caught at compile time.
08

Model API request state with a discriminated union.

Save to ▾
Show answer
A shared status field lets TypeScript narrow each case: type ApiState<T> = | { status: 'idle' } | { status: 'loading' } | { status: 'success'; data: T } | { status: 'error'; message: string }; function render(state: ApiState<string[]>) { switch (state.status) { case 'success': return state.data.join(', '); case 'error': return 'Error: ' + state.message; default: return 'Loading...'; } } Impossible states, like having both data and an error, cannot be represented.
09

Create a typed fetch helper with generics.

Save to ▾
Show answer
Let callers specify the expected response type: async function getJson<T>(url: string): Promise<T> { const res = await fetch(url); if (!res.ok) throw new Error(`Request failed: ${res.status}`); return res.json() as Promise<T>; } interface Course { id: number; title: string; } const courses = await getJson<Course[]>('/api/courses'); courses[0].title.toUpperCase(); The cast trusts the server, so for untrusted data validate with a schema library like Zod before returning.
10

Write a custom type guard to check if a value is a User.

Save to ▾
Show answer
A function returning value is User narrows the type: interface User { id: number; email: string; } function isUser(value: unknown): value is User { return typeof value === 'object' && value !== null && 'id' in value && typeof (value as User).id === 'number' && 'email' in value && typeof (value as User).email === 'string'; } const data: unknown = JSON.parse(raw); if (isUser(data)) console.log(data.email); Inside the if block, data is treated as User.
11

Write a DeepReadonly type using mapped and conditional types.

Save to ▾
Show answer
Recursively mark nested properties readonly: type DeepReadonly<T> = T extends (...args: any[]) => any ? T : T extends object ? { readonly [K in keyof T]: DeepReadonly<T[K]> } : T; interface Config { api: { baseUrl: string; retries: number } } const config: DeepReadonly<Config> = { api: { baseUrl: '/api', retries: 3 } }; // config.api.retries = 5; // error Functions are left untouched, and primitives end the recursion.
12

Create a type where all fields are optional except id.

Save to ▾
Show answer
Combine Pick and Partial with an intersection: interface Product { id: string; name: string; price: number; stock: number; } type ProductUpdate = Pick<Product, 'id'> & Partial<Omit<Product, 'id'>>; const update: ProductUpdate = { id: 'p1', price: 799 }; // const bad: ProductUpdate = { price: 799 }; // error: id missing This is a common pattern for PATCH request payloads, ensuring the identifier is always present.
13

Register a service worker that caches static assets with a cache-first strategy.

Save to ▾
Show answer
Register from the page, then handle install and fetch in sw.js: // main.js if ('serviceWorker' in navigator) navigator.serviceWorker.register('/sw.js'); // sw.js const CACHE = 'static-v3'; self.addEventListener('install', e => { e.waitUntil(caches.open(CACHE).then(c => c.addAll(['/', '/app.css', '/app.js']))); }); self.addEventListener('fetch', e => { e.respondWith(caches.match(e.request).then(hit => hit || fetch(e.request))); }); Changing the cache name on each release lets the activate step delete old caches.
14

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.
15

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.
16

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.
17

Detect offline status and retry queued requests when the connection returns.

Save to ▾
Show answer
Listen for online and offline events and keep a small queue: const queue = []; async function send(req) { if (!navigator.onLine) { queue.push(req); showBanner('You are offline'); return; } await fetch(req.url, req.options); } window.addEventListener('online', async () => { hideBanner(); while (queue.length) await send(queue.shift()); }); window.addEventListener('offline', () => showBanner('You are offline')); navigator.onLine can report true on captive networks, so treat failed fetches as offline too. Persist the queue in IndexedDB for reliability.
18

Create a simple custom element with Shadow DOM.

Save to ▾
Show answer
Extend HTMLElement and register a tag name containing a hyphen: class RatingStars extends HTMLElement { connectedCallback() { const value = Number(this.getAttribute('value') || 0); const root = this.attachShadow({ mode: 'open' }); root.innerHTML = `<style>span { color: var(--star-color, orange); }</style> <span role='img' aria-label='${value} out of 5'>${'*'.repeat(value)}</span>`; } } customElements.define('rating-stars', RatingStars); // usage: <rating-stars value='4'></rating-stars> The custom property lets the page theme it despite Shadow DOM isolation.
19

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.
20

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.
21

Make an embedded video keep a 16:9 ratio at any width.

Save to ▾
Show answer
The aspect-ratio property replaces the old padding-top hack: .video-embed { width: 100%; aspect-ratio: 16 / 9; border: 0; border-radius: 8px; } .avatar { width: 64px; aspect-ratio: 1; object-fit: cover; border-radius: 50%; } The browser reserves the correct height before the iframe loads, preventing layout shift, and object-fit keeps images from stretching inside fixed ratios.
22

Animate a modal smoothly when it opens without causing layout work.

Save to ▾
Show answer
Animate only transform and opacity, which run on the compositor: .modal { opacity: 0; transform: translateY(16px) scale(0.98); transition: opacity 200ms ease, transform 200ms ease; } .modal.is-open { opacity: 1; transform: none; } @media (prefers-reduced-motion: reduce) { .modal { transition: opacity 100ms linear; transform: none; } } Animating top, height or margin instead would trigger layout on every frame and cause jank on low-end phones.
23

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.
24

Write a card that changes layout based on its container width.

Save to ▾
Show answer
Use a container query so the card adapts wherever it is placed: .card-wrapper { container-type: inline-size; } .card { display: grid; gap: 1rem; } @container (min-width: 420px) { .card { grid-template-columns: 160px 1fr; align-items: center; } } In a narrow sidebar the image stacks above text; in a wide main column it sits beside the text, with no viewport media queries.
25

Collect Core Web Vitals from real users with the web-vitals library.

Save to ▾
Show answer
Report metrics to your analytics endpoint: import { onLCP, onINP, onCLS } from 'web-vitals'; function send(metric) { const body = JSON.stringify({ name: metric.name, value: metric.value, rating: metric.rating, page: location.pathname }); navigator.sendBeacon('/analytics/vitals', body); } onLCP(send); onINP(send); onCLS(send); sendBeacon delivers data reliably even when the page is closing. Aggregate at the 75th percentile per page.
26

Load a heavy module only when the user needs it.

Save to ▾
Show answer
Use a dynamic import inside the event handler: const exportBtn = document.querySelector('#export-pdf'); exportBtn.addEventListener('click', async () => { exportBtn.disabled = true; const { generatePdf } = await import('./pdf-export.js'); await generatePdf(reportData); exportBtn.disabled = false; }); The bundler creates a separate chunk for pdf-export.js, so users who never export do not download it. Prefetching on hover can hide the delay.
27

Configure cache headers for hashed assets and HTML in Nginx.

Save to ▾
Show answer
Long cache for fingerprinted files, revalidation for HTML: location ~* \.(js|css|woff2|avif|webp|svg)$ { add_header Cache-Control 'public, max-age=31536000, immutable'; } location / { try_files $uri /index.html; add_header Cache-Control 'no-cache'; } This works only when build tools add content hashes to filenames. Returning users then load assets from cache instantly, while every deploy still reaches them through fresh HTML.
28

Break a long-running loop into smaller tasks to keep the page responsive.

Save to ▾
Show answer
Yield to the main thread between chunks: function yieldToMain() { if (globalThis.scheduler?.yield) return scheduler.yield(); return new Promise(resolve => setTimeout(resolve, 0)); } async function processRows(rows) { let last = performance.now(); for (const row of rows) { processRow(row); if (performance.now() - last > 40) { await yieldToMain(); last = performance.now(); } } } The browser can handle clicks between chunks, which improves INP. scheduler.yield keeps the task's priority after resuming.
29

Add resource hints for a third-party font and the hero image.

Save to ▾
Show answer
Place these early in the head: <link rel='preconnect' href='https://fonts.gstatic.com' crossorigin> <link rel='preload' href='/fonts/inter-var.woff2' as='font' type='font/woff2' crossorigin> <link rel='preload' href='/img/hero-1200.avif' as='image' fetchpriority='high'> <link rel='dns-prefetch' href='https://analytics.example.com'> Fonts must be preloaded with crossorigin, even from the same origin, or the browser downloads them twice. Preload only a few critical resources.
30

Enforce a performance budget in CI with Lighthouse CI.

Save to ▾
Show answer
Add a lighthouserc.json with assertions: { "ci": { "collect": { "url": ["http://localhost:4173/"], "numberOfRuns": 3 }, "assert": { "assertions": { "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }], "cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }], "total-byte-weight": ["warn", { "maxNumericValue": 400000 }] } } } } Run npx lhci autorun after building. Pull requests that break the budget fail, so regressions are caught before release.
31

Create a new Vite project with TypeScript and run it.

Save to ▾
Show answer
Use the official scaffolding tool: npm create vite@latest my-app -- --template vanilla-ts cd my-app npm install npm run dev # starts the dev server with HMR npm run build # type-checks and builds to dist/ npm run preview # serves the production build locally Templates also exist for react-ts, vue-ts and svelte-ts. The dist folder contains static files ready for any web server or CDN.
32

Configure a path alias and an API proxy in Vite.

Save to ▾
Show answer
vite.config.ts: import { defineConfig } from 'vite'; import { fileURLToPath, URL } from 'node:url'; export default defineConfig({ resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } }, server: { proxy: { '/api': { target: 'http://localhost:8080', changeOrigin: true } } } }); Imports like '@/utils/format' work anywhere, and the proxy avoids CORS issues in development. Add matching paths in tsconfig for editor support.
33

Set up ESLint with the flat config for a TypeScript project.

Save to ▾
Show answer
Install packages and create eslint.config.js: // npm i -D eslint @eslint/js typescript-eslint import js from '@eslint/js'; import tseslint from 'typescript-eslint'; export default tseslint.config( js.configs.recommended, ...tseslint.configs.recommended, { rules: { '@typescript-eslint/no-explicit-any': 'warn', 'no-console': ['warn', { allow: ['error'] }] } }, { ignores: ['dist/'] } ); Run npx eslint . locally and in CI. Leave formatting to Prettier so the two tools do not conflict.
34

Split vendor libraries into separate chunks and visualise the bundle.

Save to ▾
Show answer
Use manualChunks and a visualiser plugin: import { defineConfig } from 'vite'; import { visualizer } from 'rollup-plugin-visualizer'; export default defineConfig({ plugins: [visualizer({ filename: 'stats.html', gzipSize: true })], build: { rollupOptions: { output: { manualChunks: { charts: ['chart.js'], editor: ['@tiptap/core'] } } } } }); After building, open stats.html to see which modules take the most space and decide what to lazy load or replace.
35

Run linting and formatting automatically before each commit.

Save to ▾
Show answer
Use Husky with lint-staged: npm i -D husky lint-staged npx husky init echo 'npx lint-staged' > .husky/pre-commit // package.json "lint-staged": { "*.{ts,tsx,js}": ["eslint --fix", "prettier --write"], "*.{css,md,json}": "prettier --write" } Only staged files are checked, so commits stay fast. CI should still run the full lint because hooks can be skipped locally.
36

Write a GitHub Actions workflow that lints, tests and builds a frontend app.

Save to ▾
Show answer
A typical CI pipeline: name: CI on: [pull_request] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 cache: npm - run: npm ci - run: npm run lint - run: npm test -- --run - run: npm run build npm ci installs exactly from the lockfile, and caching speeds up repeat runs. Branch protection can require this check before merging.
37

Write a Vitest unit test for an INR price formatter.

Save to ▾
Show answer
Test normal, edge and invalid inputs: // format.ts export const formatINR = (paise: number) => new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(paise / 100); // format.test.ts import { describe, it, expect } from 'vitest'; import { formatINR } from './format'; describe('formatINR', () => { it('formats lakhs with Indian grouping', () => { expect(formatINR(12345600)).toBe('\u20b91,23,456.00'); }); it('handles zero', () => { expect(formatINR(0)).toBe('\u20b90.00'); }); });
38

Mock fetch in a Vitest test to check error handling.

Save to ▾
Show answer
Stub the global fetch and assert behaviour: import { it, expect, vi, afterEach } from 'vitest'; import { loadCourses } from './api'; afterEach(() => vi.unstubAllGlobals()); it('returns an empty list when the server fails', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue( new Response('Server error', { status: 500 }) )); const result = await loadCourses(); expect(result).toEqual([]); expect(fetch).toHaveBeenCalledWith('/api/courses'); }); For larger suites, MSW handlers are cleaner than stubbing fetch in every test.
39

Write a Playwright end-to-end test for a login flow.

Save to ▾
Show answer
Use role-based locators and web-first assertions: import { test, expect } from '@playwright/test'; test('user can log in and see dashboard', async ({ page }) => { await page.goto('/login'); await page.getByLabel('Email').fill('student@example.com'); await page.getByLabel('Password').fill('Secret@123'); await page.getByRole('button', { name: 'Log in' }).click(); await expect(page).toHaveURL(/dashboard/); await expect(page.getByRole('heading', { name: 'My courses' })).toBeVisible(); }); Assertions auto-wait, so no manual sleeps are needed. Save login state with storageState to reuse in other tests.
40

Test a DOM form with Testing Library and user-event.

Save to ▾
Show answer
Simulate real typing and clicks: import { screen } from '@testing-library/dom'; import userEvent from '@testing-library/user-event'; import { mountSignupForm } from './signup'; it('shows an error for an invalid mobile number', async () => { document.body.innerHTML = '<div id=app></div>'; mountSignupForm(document.getElementById('app')); const user = userEvent.setup(); await user.type(screen.getByLabelText('Mobile'), '12345'); await user.click(screen.getByRole('button', { name: 'Sign up' })); expect(screen.getByRole('alert')).toHaveTextContent('Enter a valid mobile number'); }); toHaveTextContent comes from @testing-library/jest-dom.
41

Add automated accessibility checks to Playwright tests.

Save to ▾
Show answer
Use the axe-core integration: import { test, expect } from '@playwright/test'; import AxeBuilder from '@axe-core/playwright'; test('home page has no serious accessibility violations', async ({ page }) => { await page.goto('/'); const results = await new AxeBuilder({ page }) .withTags(['wcag2a', 'wcag2aa']) .analyze(); const serious = results.violations.filter(v => ['serious', 'critical'].includes(v.impact)); expect(serious).toEqual([]); }); Automated tools catch only part of accessibility issues, so keyboard and screen reader checks are still needed.
42

Write a minimal observable store in plain JavaScript.

Save to ▾
Show answer
A store holds state and notifies subscribers: function createStore(initial) { let state = initial; const listeners = new Set(); return { get: () => state, set(update) { state = { ...state, ...update }; listeners.forEach(fn => fn(state)); }, subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); } }; } const cart = createStore({ items: 0 }); const stop = cart.subscribe(s => (badge.textContent = s.items)); cart.set({ items: 2 }); The returned unsubscribe function prevents memory leaks.
43

Implement simple feature flags on the frontend.

Save to ▾
Show answer
Load flags once and check them where needed: let flags = {}; export async function loadFlags(userId) { const res = await fetch('/api/flags?user=' + encodeURIComponent(userId)); flags = res.ok ? await res.json() : {}; } export const isEnabled = (name) => flags[name] === true; // usage await loadFlags(currentUser.id); if (isEnabled('new-checkout')) renderNewCheckout(); else renderOldCheckout(); Defaulting to off when the request fails keeps the stable path. Flags enable gradual rollouts, but old flags must be removed to avoid clutter.
44

Write a React custom hook that fetches data and cancels on unmount.

Save to ▾
Show answer
Use AbortController inside useEffect: import { useEffect, useState } from 'react'; export function useFetch(url) { const [state, setState] = useState({ data: null, error: null, loading: true }); useEffect(() => { const controller = new AbortController(); setState(s => ({ ...s, loading: true })); fetch(url, { signal: controller.signal }) .then(r => (r.ok ? r.json() : Promise.reject(new Error(r.status)))) .then(data => setState({ data, error: null, loading: false })) .catch(err => { if (err.name !== 'AbortError') setState({ data: null, error: err, loading: false }); }); return () => controller.abort(); }, [url]); return state; } In production apps, TanStack Query adds caching and retries.
45

Build an API client that refreshes an expired access token once and retries.

Save to ▾
Show answer
Share one refresh promise so parallel requests do not refresh repeatedly: let refreshing = null; async function api(path, options = {}) { let res = await fetch(path, { ...options, credentials: 'include' }); if (res.status !== 401) return res; refreshing ??= fetch('/auth/refresh', { method: 'POST', credentials: 'include' }) .finally(() => (refreshing = null)); const refreshed = await refreshing; if (!refreshed.ok) { location.assign('/login'); throw new Error('Session expired'); } return fetch(path, { ...options, credentials: 'include' }); } Cookies carry the tokens, so JavaScript never reads them.

Frequently asked questions

Why are practical questions important?

Most technical rounds include at least one live task. Practising the exact typing and reasoning makes you calm and fast in the real round.

How should I answer them?

Talk while you work: say your approach first, write the simplest correct version, then improve it and mention edge cases.