24 role-specific questions
Frontend Developer Interview Questions & Answers
Frontend interviews test whether you can build fast, accessible interfaces that work in every browser — and whether you understand what happens underneath your framework. Expect questions on JavaScript fundamentals, CSS layout, accessibility and web performance, plus your framework of choice.
Free, no sign-up. 110 questions in this role's practice pool, including behavioural, HR and situational questions.
HTML, CSS & the browser interview questions
Semantics, accessibility, CSS layout, web performance and how browsers render — the fundamentals behind every front-end role.
1.
Why does semantic HTML matter? Give examples.
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Accessibility and quality awareness, not just visual output.
Key points a strong answer covers
- Meaningful elements. Use elements for their meaning:
<nav>,<main>,<button>,<article>. - Accessibility. Assistive technology relies on semantics for landmarks, roles and keyboard behaviour.
- SEO / machines. Search engines and other tools understand the structure better.
- div button problem. A clickable
<div>isn't focusable or keyboard operable;<button>is, for free.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using headings for font size rather than structure.
- Building buttons from divs.
Likely follow-up questions
- What does a
<button>give you that a<div onClick>doesn't? - How should heading levels be structured on a page?
Example strong answer
Semantic HTML means using elements for what they are, not how they look:
<header>,<nav>,<main>,<article>,<button>, a single logical heading outline. It matters mostly for accessibility: screen-reader users jump between landmarks and headings, and a real<button>is focusable, announced as a button and works with Enter and Space automatically — a<div onClick>gives you none of that. It also helps search engines understand the page and makes the code easier to read. Accessibility audits I've done usually find most problems come from non-semantic markup, so fixing that first is cheap and effective.- Meaningful elements. Use elements for their meaning:
2.
How do you make a web application accessible?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical accessibility knowledge beyond buzzwords.
Key points a strong answer covers
- Semantics first. Native elements and proper labels before ARIA.
- Keyboard. Everything usable by keyboard with a visible focus; manage focus in dialogs.
- Contrast / text. Sufficient contrast, alt text, text that resizes.
- ARIA used carefully. ARIA only when there's no native equivalent; live regions for updates.
- Testing. Test with axe/Lighthouse and a real screen reader; follow WCAG 2.2 AA.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Adding ARIA to everything instead of using native elements.
- Relying only on automated tools.
Likely follow-up questions
- How would you build an accessible modal dialog?
- What can automated tools not catch?
Example strong answer
I start with semantics: native elements, labelled form fields and a sensible heading structure — that solves most issues. Then keyboard: every action reachable by Tab, a visible focus style, and focus managed properly in modals and menus — moved in on open, trapped, returned on close. Colour contrast of at least 4.5:1 for body text, meaningful alt text, and layouts that survive 200% zoom. ARIA only where there's no native option —
aria-livefor toast messages,aria-expandedon a disclosure. I test with axe in CI, then manually with the keyboard and VoiceOver or NVDA, because automated tools catch maybe a third of issues. WCAG 2.2 AA is the usual target.3.
Explain the CSS box model and
box-sizing: border-box.BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand how element sizes are calculated — the root of many layout bugs.
Key points a strong answer covers
- Four layers. Every box is content, padding, border and margin.
- content-box default. By default width applies to the content, so padding and border make it wider.
- border-box. border-box makes width include padding and border — easier to reason about.
- Margin collapse. Vertical margins between blocks can collapse.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Not knowing why an element with width: 100% and padding overflows.
- Forgetting margin collapsing.
Likely follow-up questions
- When do vertical margins collapse?
- How does
box-sizingaffect a flex item's size?
Example strong answer
Every element is a box made of content, then padding, then border, then margin outside. With the default
box-sizing: content-box,widthsets only the content, so awidth: 100%element with 20px padding ends up wider than its parent and overflows. Withborder-box,widthincludes padding and border, so the element is exactly the width you set — that's why most resets apply*, *::before, *::after { box-sizing: border-box }. Margins sit outside the border and don't count, and adjacent vertical margins between blocks can collapse into one, which surprises people.4.
When would you use Flexbox and when CSS Grid?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you choose the layout tool that fits the problem rather than forcing one everywhere.
Key points a strong answer covers
- Flexbox one dimension. Flexbox lays items out along one axis.
- Grid two dimensions. Grid controls rows and columns together.
- Content vs layout first. Flex is content-driven; Grid defines the layout and places content into it.
- Examples. Flex for toolbars and nav bars; Grid for page layouts, galleries, card grids.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using Grid or Flex dogmatically for everything.
- Not knowing
gapworks in Flexbox too.
Likely follow-up questions
- How would you build a responsive card grid without media queries?
- How do you centre an element both ways?
Example strong answer
Flexbox is for one dimension — a row or a column — and it's content-driven: items size themselves and you distribute space, which is perfect for a nav bar, a toolbar, or aligning an icon with text. Grid is two-dimensional: you define rows and columns and place items into them, so it suits page layouts, dashboards and card galleries —
grid-template-columns: repeat(auto-fill, minmax(220px, 1fr))gives a responsive card grid without media queries. They combine well: a Grid page layout with Flexbox inside each card. Both supportgap, and centring is justdisplay: grid; place-items: center.5.
What happens between typing a URL and seeing the page? Focus on how the browser renders it.
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
End-to-end understanding of loading and rendering.
Key points a strong answer covers
- Network. DNS lookup, connection (TCP/TLS), HTTP request, response.
- Parse HTML / DOM. The browser parses HTML into the DOM.
- CSSOM / render blocking. CSS builds the CSSOM; CSS and synchronous scripts block rendering.
- Layout and paint. DOM + CSSOM → render tree → layout → paint → composite.
- Scripts. Use defer/async so scripts don't block parsing.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Skipping the network part entirely.
- Not mentioning what blocks rendering.
Likely follow-up questions
- What's the difference between
asyncanddefer? - What causes a layout (reflow), and why is it expensive?
Example strong answer
First the network: a DNS lookup, then a TCP and TLS connection, then the HTTP request — often served by a CDN. As the HTML streams in, the browser parses it into the DOM and discovers other resources. CSS is render-blocking: the browser builds the CSSOM before it paints. A plain
<script>blocks parsing too, which is why I usedeferor modules. The DOM and CSSOM combine into a render tree; layout calculates each box's position and size; paint fills pixels; and compositing assembles layers on the GPU. To speed it up: small critical CSS, deferred scripts, preloading the LCP image and fonts, and avoiding layout-triggering work after load.6.
What are Core Web Vitals, and how would you improve each one?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Measurable performance knowledge.
Key points a strong answer covers
- LCP. LCP measures loading — when the largest content element appears (good ≤ 2.5s).
- INP. INP measures responsiveness to interactions (good ≤ 200ms). It replaced FID.
- CLS. CLS measures visual stability (good ≤ 0.1).
- Fixes. LCP: optimise and preload the hero; INP: break up long tasks; CLS: reserve space for media and ads.
- Field data. Measure with field data (CrUX, RUM), not only Lighthouse.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Still citing FID as the responsiveness metric.
- Only quoting Lighthouse lab scores.
Likely follow-up questions
- What's the difference between lab and field data?
- What usually causes a poor INP?
Example strong answer
Core Web Vitals are Google's user-centred metrics. LCP, Largest Contentful Paint, measures loading — good is 2.5 seconds or less; I improve it by serving a compressed, correctly sized hero image, preloading it, using a CDN and removing render-blocking resources. INP, Interaction to Next Paint, replaced FID and measures responsiveness — good is 200 ms or less; it's usually hurt by long JavaScript tasks, so I split work up, defer non-essential scripts and reduce hydration cost. CLS measures layout shift — good is 0.1 or less; I reserve space for images, ads and embeds and avoid font swaps that shift text. I track field data from real users, not just Lighthouse.
7.
What is CORS, and why do you get CORS errors?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding of the same-origin policy and where to fix CORS issues.
Key points a strong answer covers
- Same-origin policy. Browsers block reading responses from a different origin by default.
- Server opts in. The server opts in with Access-Control-Allow-Origin and related headers.
- Preflight. Non-simple requests trigger an OPTIONS preflight first.
- Fix on the server. It's fixed on the server (or via a proxy), not in front-end code.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Trying to fix CORS in the frontend fetch call.
- Setting
Access-Control-Allow-Origin: *with credentials.
Likely follow-up questions
- Why doesn't Postman show CORS errors?
- What changes when the request includes cookies?
Example strong answer
CORS is a relaxation of the browser's same-origin policy. By default a page on
app.example.comcan send a request toapi.other.com, but the browser won't let the JavaScript read the response unless the server says it's allowed, with headers likeAccess-Control-Allow-Origin. For non-simple requests — say a PUT, or a JSON content type, or a custom header — the browser first sends an OPTIONS preflight to ask permission. So a CORS error is fixed on the server: allow the specific origin, methods and headers, or route through a same-origin proxy. Tools like Postman don't enforce it because it's a browser rule. With cookies you needcredentials: 'include'and a specific origin, not*.8.
Compare cookies, localStorage, sessionStorage and IndexedDB.
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Choosing client storage safely.
Key points a strong answer covers
- Cookies sent to server. Cookies go with every request to their domain; httpOnly cookies are invisible to JavaScript.
- localStorage persists. localStorage persists, is synchronous, string-only, ~5MB per origin.
- sessionStorage per tab. sessionStorage is cleared when the tab closes.
- IndexedDB. IndexedDB is async and stores large structured data and blobs.
- Security. Don't keep auth tokens where XSS can read them; prefer httpOnly cookies.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Storing JWTs in localStorage without considering XSS.
- Storing large data in cookies.
Likely follow-up questions
- Why is localStorage a poor place for an auth token?
- When would you reach for IndexedDB?
Example strong answer
Cookies are small and sent automatically with every request to their domain, which makes them the right place for a session — as httpOnly, Secure and SameSite, JavaScript can't read them, which protects against token theft through XSS. localStorage persists across sessions, is synchronous and string-only with roughly 5 MB per origin — fine for preferences like the theme, but any script on the page can read it, so not for tokens. sessionStorage is the same but per tab and cleared when it closes — handy for a form draft. IndexedDB is asynchronous and stores large structured data and files, which is what offline apps and editors use.
9.
How do you protect a front-end application against XSS and CSRF?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Security awareness for the client side.
Key points a strong answer covers
- XSS = injected script. XSS is untrusted content executing as script in your page.
- Escape / avoid raw HTML. Frameworks escape by default; avoid raw HTML or sanitise it (DOMPurify).
- CSP. A Content Security Policy limits which scripts can run.
- CSRF. CSRF tricks a logged-in browser into sending a request.
- CSRF defences. SameSite cookies, CSRF tokens and checking the Origin header.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Thinking React makes XSS impossible.
- Confusing CSRF with XSS.
Likely follow-up questions
- How can XSS still happen in a React app?
- Why do SameSite cookies help against CSRF?
Example strong answer
XSS is when untrusted content runs as script in your page — a comment containing
<script>or anonerrorattribute. React and other frameworks escape text by default, so the risks are the escape hatches:dangerouslySetInnerHTML,innerHTML, andjavascript:URLs in links. I avoid raw HTML, and when I must render it — rich text from a CMS — I sanitise it with DOMPurify. A Content Security Policy is a second layer that blocks inline and unknown scripts. CSRF is different: another site makes the user's browser send a request with their cookies. SameSite=Lax or Strict cookies block most of it, and for sensitive actions I add CSRF tokens or check the Origin header.10.
How do you build a responsive layout?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical mobile-first CSS.
Key points a strong answer covers
- Mobile first. Start with the small-screen layout and add breakpoints with min-width.
- Fluid units. Use fluid units, clamp() and fr instead of fixed pixels.
- Flexible layout. Grid and Flexbox that wrap naturally.
- Responsive media. Images with max-width: 100% and srcset/sizes.
- Container queries / testing. Container queries for components; test on real devices.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Designing desktop first and patching mobile.
- Fixed-width containers causing horizontal scroll.
Likely follow-up questions
- What do container queries solve that media queries don't?
- Why use rem for font sizes?
Example strong answer
I work mobile first: base styles for small screens, then
min-widthbreakpoints where the content needs them rather than for specific devices. Layouts use Grid and Flexbox that wrap on their own —repeat(auto-fill, minmax(…))handles a lot without breakpoints — with fluid units like %, fr and rem, andclamp()for typography that scales smoothly. Images getmax-width: 100%andsrcsetwithsizesso phones download smaller files. For components that appear in different widths, like a card in a sidebar or main column, container queries are better than viewport media queries. I check for horizontal scrolling and test on real phones, not just DevTools.
JavaScript interview questions
Closures, the event loop, async code, scope and the prototype chain — the core of every front-end and Node.js interview.
1.
Explain closures in JavaScript, with a practical example.
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand lexical scope and can connect it to real code, not just recite a definition.
Key points a strong answer covers
- Function + outer scope. A closure is a function bundled with references to the variables of the scope it was created in.
- Variables stay alive. The captured variables live on after the outer function returns.
- Practical use. Private state, factories, memoisation, debounce/throttle and event handlers all rely on closures.
- Pitfall. Watch for stale values (e.g. in React effects),
varin loops, and accidentally retaining large objects.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying a closure is “a function inside a function” without explaining what it captures.
- No example — interviewers want to see you've used one.
Likely follow-up questions
- What does
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))print, and why? - How can a closure cause a memory leak?
Example strong answer
A closure is a function together with the variables from the scope where it was defined. Because the function keeps a reference to that scope, those variables stay alive even after the outer function has returned. A simple example is a counter factory:
makeCounter()declareslet count = 0and returns a function that increments it — each counter has its own privatecount. I use closures every day for event handlers, debounce helpers and module-private state. The main pitfall is stale values: a React effect or a timer can capture an old variable, so you need the right dependencies or a ref.2.
What is the event loop, and how do microtasks differ from macrotasks?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you can predict the order async code runs in, which matters for debugging race conditions and UI jank.
Key points a strong answer covers
- Single thread + call stack. JavaScript runs one call stack on a single thread; the event loop decides what runs next.
- Task queue. Timers, I/O and UI events queue (macro)tasks.
- Microtasks first. After each task, all queued microtasks (promise callbacks, await continuations) run before the next task.
- Rendering / blocking. Long synchronous work or endless microtasks block rendering.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
setTimeout(fn, 0)runs immediately. - Forgetting that microtasks drain completely before the browser can paint.
Likely follow-up questions
- In what order do
console.log,setTimeoutandPromise.resolve().thenlog? - How would you break up a long-running loop so the page stays responsive?
Example strong answer
JavaScript runs on one thread with one call stack. The event loop takes the next task — a timer callback, an I/O completion or a UI event — and runs it to completion. After every task it drains the microtask queue, which holds promise reactions and
awaitcontinuations, and only then can the browser render and pick the next task. Soconsole.log('a'); setTimeout(() => log('b')); Promise.resolve().then(() => log('c')); log('d')prints a, d, c, b. In practice that's why a heavy synchronous loop freezes the UI; I split long work into chunks withsetTimeoutorscheduler.yield, or move it to a Web Worker.3.
What's the difference between var, let and const?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Basic language fluency: scope, hoisting and immutability of bindings.
Key points a strong answer covers
- Function vs block scope.
varis function-scoped;letandconstare block-scoped. - Hoisting / TDZ. All are hoisted, but
varis initialised to undefined whilelet/constsit in the temporal dead zone until declared. - const binding, not value.
conststops reassignment, not mutation — a const object can still change. - Re-declaration.
varallows re-declaration in the same scope;let/constdon't.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Claiming
constmakes objects immutable. - Saying
letandconstaren't hoisted at all.
Likely follow-up questions
- How would you make an object truly read-only?
- Why does
varin a for-loop cause bugs with callbacks?
Example strong answer
varis function-scoped, can be re-declared, and is hoisted and initialised toundefined, so you can read it before the declaration line.letandconstare block-scoped; they're hoisted too, but they're in the temporal dead zone until the declaration runs, so early access throws.constprevents reassigning the binding, not changing the value —const user = {}can still get new properties; for a read-only object you'd useObject.freeze, which is shallow. In modern code I default toconst, useletwhen a value really changes, and avoidvar.- Function vs block scope.
4.
Explain promises and async/await. How do you handle errors and run requests in parallel?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical async skills: error handling, sequencing and concurrency.
Key points a strong answer covers
- Promise states. A promise is pending, then fulfilled or rejected, once.
- async/await is syntax over promises. An async function returns a promise;
awaitpauses that function until the promise settles. - Error handling. Use try/catch around awaits (or
.catch), and never leave a rejection unhandled. - Parallel vs sequential. Awaiting in a loop is sequential;
Promise.allruns them together;allSettledwaits for every result.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Awaiting independent requests one by one, making the page slower.
- Using
Promise.allwithout considering that one rejection fails the whole batch.
Likely follow-up questions
- When would you choose
Promise.allSettledoverPromise.all? - How would you limit concurrency to five requests at a time?
Example strong answer
A promise represents a value that will arrive later; it's pending, then fulfilled or rejected exactly once.
async/awaitis syntax over promises: an async function always returns a promise, andawaitpauses just that function until the promise settles, so code reads top to bottom. For errors I wrap awaits in try/catch, or attach.catchwhen I'm not awaiting. If requests don't depend on each other I start them together withPromise.all, which rejects as soon as one fails; when I need every outcome — say, uploading ten files and reporting which failed — I usePromise.allSettled. For large batches I limit concurrency with a small pool.5.
How is the value of
thisdetermined in JavaScript?IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Whether you understand call-site binding — a frequent source of bugs in callbacks and classes.
Key points a strong answer covers
- Depends on the call.
thisis set by how a function is called, not where it's written. - Method / default binding.
obj.fn()sets this to obj; a plain call gives undefined in strict mode (the global object otherwise). - Explicit binding.
call,applyandbindsetthisexplicitly. - Arrow functions. Arrow functions don't have their own
this; they use the enclosing scope's. - new. With
new,thisis the newly created object.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
thisrefers to the function itself. - Not knowing why a method loses
thiswhen passed as a callback.
Likely follow-up questions
- Why does
setTimeout(obj.method, 100)losethis, and how do you fix it? - When would you avoid an arrow function as an object method?
Example strong answer
thisis decided by the call, not the definition. Called as a method —user.greet()—thisisuser. Called as a plain function, it'sundefinedin strict mode or the global object otherwise.call,applyandbindset it explicitly, and withnewit's the newly created instance. Arrow functions don't bind their ownthis; they take it from the surrounding scope, which is why they're handy in callbacks inside class methods. A classic bug is passingobj.methodtosetTimeoutor an event listener: it's called without the object, sothisis lost — fix it withobj.method.bind(obj)or an arrow wrapper.- Depends on the call.
6.
Explain prototypal inheritance. How do ES6 classes relate to it?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Depth of language knowledge beyond syntax.
Key points a strong answer covers
- Prototype chain. Objects link to a prototype; property lookups walk up the chain until found or null.
- Shared methods. Methods on the prototype are shared by all instances rather than copied.
- Classes are syntax.
classis mostly syntax over constructor functions and prototypes. - Creating links.
Object.create, constructor functions andextendsset up the prototype link.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Describing JavaScript classes as if they copy methods like Java classes.
- Confusing
prototype(on functions) with an object's internal prototype.
Likely follow-up questions
- What's the difference between
Foo.prototypeandObject.getPrototypeOf(foo)? - How does
hasOwnPropertydiffer from theinoperator?
Example strong answer
Every object has an internal link to another object, its prototype. When you read a property that isn't on the object itself, JavaScript looks it up on the prototype, then that object's prototype, and so on until it reaches
null. That's how inheritance works: methods live once on a prototype and every instance shares them. ES6 classes are largely syntax over this —class Admin extends UsersetsAdmin.prototype's prototype toUser.prototype, and methods in the class body go on the prototype. You can also link objects directly withObject.create(proto). Knowing this helps when debugginginstanceofor checking own properties withObject.hasOwn.7.
What is event delegation, and why is it useful?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
DOM fundamentals and awareness of performance with many elements.
Key points a strong answer covers
- Bubbling. Most events bubble from the target up through its ancestors.
- One listener on a parent. Attach one listener to a common parent instead of one per child.
- Identify the target. Use
event.target.closest(selector)to find which child was clicked. - Benefits. Works for elements added later and uses fewer listeners.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
event.targetdirectly when the click lands on a nested icon inside the button. - Forgetting events like
focusdon't bubble (usefocusin).
Likely follow-up questions
- What's the difference between
event.targetandevent.currentTarget? - How do
stopPropagationandpreventDefaultdiffer?
Example strong answer
Events bubble: a click on a list item also fires on the list and every ancestor. Event delegation uses that by putting one listener on a parent — say the
<ul>of a long to-do list — and working out which child was clicked withevent.target.closest('li'). It means fewer listeners and it automatically handles items added later, which is ideal for tables or infinite lists. Two things to watch: useclosestbecause the target might be an icon inside the button, and some events such asfocusdon't bubble, so you'd usefocusininstead.8.
What's the difference between
==and===? What aboutObject.is?BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Precision about type coercion.
Key points a strong answer covers
- Coercion.
==converts types before comparing;===doesn't. - Strict equality.
===requires the same type and value. - Edge cases.
null == undefinedis true;NaN === NaNis false; objects compare by reference. - Object.is.
Object.isis like===but treats NaN as equal to itself and +0/-0 as different.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying
==compares values and===compares references. - Not mentioning that objects are compared by reference with both.
Likely follow-up questions
- Why is
[] == falsetrue? - How would you compare two objects by their contents?
Example strong answer
===is strict equality: same type and same value, no conversion.==applies type coercion first, which produces surprises like'0' == falseand[] == falseboth being true. The one coercion I find genuinely useful isx == null, which catches both null and undefined. Objects and arrays are compared by reference with either operator, so two identical-looking objects aren't equal.Object.isis like===exceptObject.is(NaN, NaN)is true andObject.is(0, -0)is false. In code I use===by default and lint against==.- Coercion.
9.
What's the difference between debounce and throttle? When would you use each?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Practical performance techniques for event-heavy UIs.
Key points a strong answer covers
- Debounce waits for a pause. Debounce runs once after events stop for a set time.
- Throttle limits rate. Throttle runs at most once per interval while events keep firing.
- Use cases. Debounce: search-as-you-type, autosave. Throttle: scroll, resize, mousemove.
- Implementation. Both are built with timers (and a closure holding the timer id).
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Mixing up which is which.
- Debouncing scroll position tracking so it only updates after the user stops.
Likely follow-up questions
- How would you implement debounce in a few lines?
- What does a leading-edge debounce do?
Example strong answer
Both limit how often a function runs during a burst of events. Debounce waits until the events stop for, say, 300 ms and then runs once — ideal for search-as-you-type so you send one request when the user pauses, or for autosave. Throttle runs at most once per interval while the events keep coming — good for scroll or resize handlers that need regular updates. Debounce is a closure holding a timer: each call clears the previous timeout and sets a new one. Throttle tracks the last run time or uses a timer flag. Where available,
requestAnimationFrameis often the best throttle for visual updates.10.
How do you copy an object in JavaScript? What's the difference between a shallow and a deep copy?
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Understanding of references and immutable update patterns.
Key points a strong answer covers
- Shallow copy. Spread and
Object.assigncopy only the top level; nested objects are still shared. - Deep copy. A deep copy duplicates nested objects too;
structuredClonedoes this natively. - JSON trick limits.
JSON.parse(JSON.stringify(x))loses dates, functions, undefined, Maps and cycles. - Why it matters. Accidental shared references cause state bugs, especially in React/Redux.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Thinking spread makes a full independent copy.
- Recommending the JSON trick without its limitations.
Likely follow-up questions
- What can't
structuredClonecopy? - How would you update a nested property immutably?
Example strong answer
Assigning an object just copies the reference. Spread (
{...obj}) andObject.assignmake a shallow copy: the top-level properties are new, but nested objects are still shared, so changingcopy.address.citychanges the original. For a deep copy I usestructuredClone, which handles nested objects, arrays, Dates, Maps and even cycles — but not functions or DOM nodes. The oldJSON.parse(JSON.stringify())trick loses dates, undefined and functions. In React state I usually don't deep copy at all; I copy just the path I'm changing, like{...user, address: {...user.address, city}}.- Shallow copy. Spread and
11.
Compare ES modules and CommonJS.
IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Familiarity with tooling and how code is loaded in browsers and Node.
Key points a strong answer covers
- Syntax. ESM uses import/export; CommonJS uses require and module.exports.
- Static vs dynamic. ESM imports are static, enabling tree shaking; require is a runtime call.
- Loading. ESM loads asynchronously and supports top-level await; CommonJS loads synchronously.
- Interop. Node chooses via
"type": "module"or .mjs/.cjs; interop has rough edges.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Not knowing why tree shaking needs static imports.
- Ignoring that exports in ESM are live bindings.
Likely follow-up questions
- What is a dynamic
import()used for? - Why might a library ship both ESM and CommonJS builds?
Example strong answer
ES modules use
importandexport; CommonJS usesrequireandmodule.exports. ESM imports are static — they're resolved before the code runs — so bundlers can tree-shake unused exports, and the browser supports ESM natively.requireis an ordinary synchronous function call at runtime, which is flexible but harder to analyse. ESM loads asynchronously, supports top-level await and exports live bindings. In Node, the package's"type"field or the .mjs/.cjs extension decides which system a file uses. For code splitting I use dynamicimport(), which returns a promise.12.
How do memory leaks happen in a JavaScript application, and how would you find one?
AdvancedTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Debugging maturity on long-lived single-page apps.
Key points a strong answer covers
- Garbage collection basics. Memory is freed when objects become unreachable; leaks are unwanted references.
- Common causes. Forgotten listeners, intervals, subscriptions, growing caches, globals and detached DOM nodes.
- Tools. Compare heap snapshots in DevTools and look at retainers.
- Fixes. Clean up in teardown (effects' cleanup), use AbortController, WeakMap for caches.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Saying JavaScript can't leak because it's garbage collected.
- No method — guessing instead of measuring.
Likely follow-up questions
- What's a detached DOM node?
- How does
AbortControllerhelp clean up listeners?
Example strong answer
JavaScript is garbage collected, so a leak is really an unwanted reference that keeps objects reachable. Common causes in SPAs are event listeners or intervals that are never removed when a component unmounts, subscriptions that aren't cancelled, caches that only grow, and detached DOM nodes still referenced from JS. To find one I reproduce the action several times — open and close a modal ten times — take heap snapshots before and after in Chrome DevTools, and compare what's growing, then follow the retainers to the code holding it. Fixes are cleanup functions in effects,
AbortControllersignals for listeners and fetches, and WeakMap for object-keyed caches.13.
When would you use map, filter, reduce and forEach?
BeginnerTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Idiomatic, readable code and understanding of immutability.
Key points a strong answer covers
- map transforms.
mapreturns a new array of the same length with each item transformed. - filter selects.
filterreturns a new array with the items that pass a test. - reduce accumulates.
reducecombines items into one value — a total, an object, a group-by. - forEach for side effects.
forEachis for side effects and returns undefined; it can't be chained or broken out of.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Using
mapjust to loop (and ignoring the returned array). - Writing unreadable reduce calls when map + filter is clearer.
Likely follow-up questions
- How would you group an array of orders by customer?
- Which of these mutate the original array?
Example strong answer
maptransforms every item and returns a new array of the same length — turning API records into view models, for example.filterreturns the items that pass a test, like active users.reducefolds the array into one value: a sum, a lookup object, or grouping orders by customer.forEachis for side effects such as logging; it returns undefined and you can't break out of it. None of them mutate the original array, which suits React state. I prefer a readablefilterthenmapover a cleverreduce, and for very large data I'd use a single loop.- map transforms.
14.
Does
fetchreject on a 404 or 500 response? How do you handle HTTP errors properly?IntermediateTechnicalPractise this question and get feedbackWhat the interviewer is evaluating
Real-world API handling and robustness.
Key points a strong answer covers
- Only network errors reject. fetch only rejects on network failures; HTTP errors still resolve.
- Check response.ok. Check
response.okor the status code and throw yourself. - Timeouts / aborts. Use AbortController (or
AbortSignal.timeout) for timeouts and cancellation. - User-facing handling. Parse the error body, show a useful message, and retry only safe requests.
Suggested answer structure
- Define it in one sentence.
- Explain how it works underneath.
- Give a practical example from code or a project.
- Close with a trade-off, pitfall or when you'd use it.
Common mistakes
- Assuming a try/catch around fetch catches 500 errors.
- Never cancelling requests when a component unmounts.
Likely follow-up questions
- How would you add a 10-second timeout?
- Which requests is it safe to retry automatically?
Example strong answer
No —
fetchonly rejects for network-level failures such as DNS errors or the connection dropping. A 404 or 500 resolves normally, so I always checkresponse.ok(or the status) and throw an error with the status and the parsed error body. I wrap that in a small API helper so every call handles it the same way. For timeouts and cancellation I pass anAbortControllersignal —AbortSignal.timeout(10000)for a deadline, and aborting on unmount so stale responses don't update the UI. I'd only auto-retry idempotent requests like GETs, with backoff.
Ready to answer them out loud?
Run a timed frontend developer mock interview, type or speak your answers, and get a score breakdown with what to improve.