Senior Frontend Developer Interview Preparation Guide - Spotify
Spotify's interview process for Senior Frontend Developers typically follows a multi-stage approach: an initial recruiter screening, a technical phone interview focusing on frontend fundamentals, a system design interview assessing architecture and scalability thinking, technical coding interviews evaluating problem-solving and code quality, behavioral interviews aligned with Spotify's culture, and a final round with senior stakeholders. The process emphasizes building scalable systems, React/TypeScript proficiency, performance optimization, and cross-functional collaboration.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with Spotify recruiter to discuss your background, career goals, and fit with the role. This is your chance to learn about the team, culture, and role expectations. The recruiter will validate your interest, compensation expectations, and availability. They may ask about your experience with large-scale systems, React ecosystem, and why you're interested in Spotify.
Tips & Advice
Be genuine and specific. Research Spotify's mission and products before the call. Prepare 2-3 thoughtful questions about the Commerce Platform team and role scope. Mention specific features of Spotify you admire and use. Highlight experience with high-scale user-facing systems. Be clear about your career motivation and what excites you about this specific role.
Focus Topics
Spotify Product Knowledge
Demonstrate familiarity with Spotify's products, features, and technical challenges in streaming and commerce
Practice Interview
Study Questions
Role Alignment and Motivation
Clearly explain why this specific role, team, and company excite you
Practice Interview
Study Questions
Background and Career Narrative
Articulate your career progression, key projects led, and growth as a Senior Frontend Developer
Practice Interview
Study Questions
Technical Phone Screen
What to Expect
First technical interview with a frontend engineer from Spotify. Focuses on core frontend fundamentals, modern web technologies, and your ability to solve problems under time constraints. Expect 1-2 coding problems requiring HTML/CSS/JavaScript expertise, questions about React patterns, performance optimization, and browser APIs. May include live coding or take-home assessment.
Tips & Advice
Master React hooks, state management patterns, and async operations. Be comfortable with JavaScript ES6+, event handling, and DOM manipulation. Explain your approach before coding. Write clean, readable code with proper error handling. Discuss trade-offs and optimization strategies. If given a choice, pick the approach you're most confident in rather than the most complex. Ask clarifying questions and communicate thinking out loud.
Focus Topics
Browser APIs and Performance
DOM manipulation, event delegation, Web APIs (Fetch, LocalStorage, etc.), performance monitoring, Core Web Vitals, optimization techniques
Practice Interview
Study Questions
JavaScript Problem Solving
Algorithm and data structure problems using JavaScript, optimal time/space complexity analysis, debugging techniques
Practice Interview
Study Questions
CSS and Responsive Design
Flexbox, Grid, media queries, responsive layouts, CSS-in-JS, performance considerations, accessibility in styling
Practice Interview
Study Questions
React Fundamentals and Hooks
Deep understanding of React hooks (useState, useEffect, useContext, useReducer), component lifecycle, and rendering optimization
Practice Interview
Study Questions
TypeScript Fundamentals
Type annotations, interfaces, generics, type inference, practical typing strategies, and integration with React
Practice Interview
Study Questions
Asynchronous JavaScript and State Management
Promises, async/await, event loop, callback patterns, managing async state in React components, and testing async operations
Practice Interview
Study Questions
System Design Interview
What to Expect
Technical interview focused on your ability to design scalable frontend systems and architectures. You'll be asked to design a user-facing feature or system (e.g., checkout flow, real-time updates, payment integration) considering performance, scalability, state management, API design, and cross-browser compatibility. Emphasis on trade-offs, caching strategies, and handling edge cases at scale.
Tips & Advice
Structure your approach: clarify requirements, discuss high-level architecture, dive into critical components. Consider performance from the start (bundle size, rendering, caching). Discuss state management strategy and API contracts. Talk about error handling, retry logic, and user experience. Mention monitoring and observability. For senior roles, interviewers expect thoughtful trade-offs and business considerations alongside technical decisions. Draw diagrams or pseudo-code if helpful.
Focus Topics
API Design and Frontend-Backend Integration
Designing frontend-friendly APIs, request/response patterns, error handling strategies, versioning, SDK design for cross-platform SDKs
Practice Interview
Study Questions
Handling Edge Cases and Error Scenarios
Network failures, timeout handling, payment failures, race conditions, browser inconsistencies, accessibility edge cases
Practice Interview
Study Questions
State Management at Scale
Choosing appropriate state management solutions (Redux, Zustand, Context), managing complex state, avoiding prop drilling, normalized state design
Practice Interview
Study Questions
Performance Optimization and Web Vitals
Code splitting, lazy loading, bundle optimization, caching strategies, rendering optimization (memoization, virtual lists), monitoring metrics like LCP, FID, CLS
Practice Interview
Study Questions
Frontend Architecture and Component Design
Designing scalable component hierarchies, separation of concerns, managing dependencies, and evolving architecture as systems grow
Practice Interview
Study Questions
Frontend Coding Deep Dive
What to Expect
Extended technical interview focused on implementing a realistic React component or feature, similar to what you'd build in the Checkout Domain. Typically involves building an interactive UI component with complex state management, API integration, error handling, and testing considerations. May include follow-up questions about code quality, refactoring, and scaling the solution.
Tips & Advice
Treat this as production code. Write clean, readable, well-commented code. Test edge cases and error scenarios. Implement proper error handling and loading states. Use TypeScript effectively. Think about accessibility (ARIA labels, keyboard navigation). Discuss testing strategy—senior developers think about testability. Be prepared to refactor based on feedback. Explain your approach before diving into code. If stuck, communicate and ask for hints—problem-solving process matters as much as the solution.
Focus Topics
Responsive and Cross-Browser Implementation
Building responsive layouts that work across devices and browsers, testing techniques, fallbacks for older browsers, touch interactions
Practice Interview
Study Questions
Developer Experience and Code Quality
Writing self-documenting code, TypeScript usage, linting, code reviews, documentation, and contributing to team standards
Practice Interview
Study Questions
Testing Frontend Code
Unit testing (Jest, React Testing Library), integration testing, mocking strategies, testing async operations, accessibility testing
Practice Interview
Study Questions
Error Handling and Loading States
Implementing robust error boundaries, retry logic, timeout handling, user-friendly error messages, skeleton screens, loading indicators
Practice Interview
Study Questions
Advanced React Patterns and Code Organization
Custom hooks, render props, compound components, higher-order components, proper use of Context, and organizing large components
Practice Interview
Study Questions
Behavioral and Cross-Functional Collaboration Interview
What to Expect
Interview with a senior engineer, tech lead, or manager assessing cultural fit, collaboration skills, and ability to work across teams. Focuses on your experience mentoring junior developers, collaborating with product and design, handling disagreements, and driving decisions. Expect questions about past projects, team dynamics, conflict resolution, and how you balance technical excellence with business needs.
Tips & Advice
Use STAR method (Situation, Task, Action, Result) for behavioral questions. Prepare stories demonstrating: mentoring junior developers, collaborating with product/design, handling technical disagreements, shipping under pressure, driving architectural improvements. At senior level, interviewers want to see how you influence without direct authority, grow team capability, and balance pragmatism with technical standards. Be specific with metrics and outcomes. Highlight listening skills and ability to understand non-technical perspectives.
Focus Topics
Handling Ambiguity and Shipping Under Pressure
Experience with unclear requirements, tight deadlines, priority conflicts, and how you maintain quality while shipping
Practice Interview
Study Questions
Technical Decision-Making and Trade-offs
How you approach technical decisions, evaluate trade-offs, involve stakeholders, and communicate rationale
Practice Interview
Study Questions
Communication and Influence
Explaining technical concepts to non-technical stakeholders, presenting ideas clearly, listening actively, and building consensus
Practice Interview
Study Questions
Mentorship and Team Development
Experience mentoring junior/mid-level engineers, improving team capabilities, code review practices, and fostering learning culture
Practice Interview
Study Questions
Cross-Functional Collaboration
Working effectively with product managers, designers, backend engineers, and data specialists; understanding different perspectives; driving alignment
Practice Interview
Study Questions
Senior Engineering Leadership and Strategic Thinking Interview
What to Expect
Final round with a principal engineer, engineering manager, or director. Assessment of your vision for the role, strategic thinking about platform evolution, ability to lead initiatives, and long-term impact potential. Discusses how you'd approach scaling frontend systems, improving developer experience, technical debt management, and contributing to team/platform strategy.
Tips & Advice
Think strategically about how you'd evolve the Checkout Domain frontend. Prepare ideas about: scaling developer experience, improving performance at scale, managing technical debt, mentoring the team to senior capabilities. Reference specific examples from your career where you've driven technical strategy or improved platform capabilities. Be honest about areas you'd need to learn. Show curiosity about Spotify's technical vision and challenges. Demonstrate how you'd balance technical excellence with business metrics (conversion rate, user trust, speed to market).
Focus Topics
Learning and Adaptability
How you stay current with frontend technologies, learn new domains (e.g., payments), and adapt to evolving requirements
Practice Interview
Study Questions
User Impact and Business Alignment
How frontend work directly impacts business metrics (conversion, trust, retention), understanding commerce metrics, optimizing for user outcomes
Practice Interview
Study Questions
Platform Evolution and Technical Strategy
Vision for evolving Checkout frontend systems, modernization initiatives, addressing technical debt while shipping features
Practice Interview
Study Questions
Scaling Developer Productivity and Experience
Improving team velocity, creating better developer tools, establishing best practices, reducing friction, fostering learning culture
Practice Interview
Study Questions
Resilience and Reliability Engineering
Building systems that handle scale, prevent revenue-impacting failures, monitoring and observability, post-incident learning
Practice Interview
Study Questions
Frequently Asked Frontend Developer Interview Questions
You inherit a system with almost no documentation, dependencies nobody wrote down, and the one engineer who understood it just left. What do you actually do in the first weeks, and how do you avoid either freezing all feature work or making the risk worse?
Sample Answer
Direct answer
The first weeks are about reducing risk cheaply, not about rewriting anything: map what the system actually does and who depends on it, put a safety net under it (monitoring and tests) before touching the code, and only then start making small, reversible changes. The goal by day 90 is not "the system is modernized," it is "the system is no longer a black box, and the org has evidence about what's safe to touch," while feature work continues in parallel rather than freezing entirely.
Structured elaboration
A workable structure:
- Days 1 to 30, discovery. Build a dependency map using a combination of static analysis (what does the code call), dynamic tracing and log correlation (what actually happens in production, which is often different from what the code suggests), and conversations with anyone who has touched the system, since undocumented tribal knowledge is itself a source you have to capture before it walks out the door. This is also when you look for lightweight, low-production-impact ways to instrument the system if it has no observability at all.
- Days 30 to 60, safety net. Add monitoring and alerting so you would actually notice if something broke, and add characterization tests, tests that pin down the system's current behavior (correct or not) so a later change that alters that behavior gets caught immediately, rather than tests that assert what the behavior should be, which requires understanding the system better than you do yet.
- Days 60 to 90, first small changes. Make a handful of low-risk, reversible improvements, fixing the most painful operational issue, extracting the most clearly separable piece, and use these as a way to validate that your dependency map and safety net actually work, before committing to anything bigger.
Throughout, the discovery approach itself matters: static analysis alone misses runtime-only dependencies (a job triggered by a cron entry nobody documented, a hidden call made only under a rare condition), so combining it with dynamic tracing, network traffic capture, and log correlation catches what static analysis alone would miss, at low production impact since these are observational techniques, not changes to the system itself.
To avoid freezing feature work: communicate explicitly that discovery and safety-net work is happening in parallel with, not instead of, feature delivery, and pick the first few changes specifically because they are small enough not to threaten the delivery timeline while still proving the approach works.
Worked example
An engineer inherits a legacy payment-reconciliation service: no documentation, three flaky integration tests, and the one person who understood it left six months ago.
- Week 1 to 2: they run static analysis to find every internal call path, and separately turn on request logging (a low-impact, purely observational change) to see what actually gets called in production. The two do not fully agree: static analysis misses a nightly batch job triggered by an external cron system nobody had documented, which the logs reveal because it shows up as unexplained traffic at 2am.
- Week 3 to 6: they build monitoring on the reconciliation service's key outputs (does the daily reconciliation total match expectations) so a regression would actually be visible, and write characterization tests around the three most business-critical code paths, capturing current behavior rather than guessing at intended behavior.
- Week 7 to 12: with the safety net in place, they fix the most painful operational issue (a memory leak that forces a weekly manual restart) as the first real change, verify the characterization tests and monitoring both catch the change as expected (a sanity check that the safety net itself works), and report back to stakeholders with an actual map of the system's dependencies and risk areas, rather than a vague "it's better now."
Trade-offs and pitfalls
The tempting shortcut is to skip straight to fixing the most obviously bad code, but without a dependency map and a safety net first, you cannot tell whether a "fix" broke something you didn't know depended on the old behavior, which is exactly how well-intentioned early changes to an undocumented system make things worse rather than better. The other trap is treating discovery as a one-time exercise rather than an ongoing habit; legacy systems that have been running for years often have dependencies that only surface under conditions (end of quarter, a specific customer's data shape) you will not see in the first 90 days no matter how thorough you are.
Given a complex interactive UI where multiple components may call preventDefault() on pointer or touch events, explain a diagnostic approach to determine which handler is preventing a native behavior (e.g., horizontal swipe). Describe code instrumentation, search patterns, and quick runtime tricks to find the culprit.
Sample Answer
Direct answer
Work from the symptom inward. First prove whether the gesture is cancelled by script (some listener called preventDefault(), the method that tells the browser not to run its built-in response to the event, here native panning) or blocked by CSS (touch-action) or by the browser's own rules, then, if it is script, make the browser tell you who called it. The fastest tool is a temporary patch of Event.prototype.preventDefault that logs the event type, the target and a stack trace for every cancelable touch or pointer event. Pair it with a search of the code base for preventDefault, passive: false and touch-action, and with the DevTools Event Listener Breakpoints for touch events.
Step 1: separate the three causes
Terms used in the steps that follow:
- Passive listener: a listener registered with
{ passive: true }, which promises never to callpreventDefault(). The browser can then start scrolling at once instead of waiting to see whether the handler cancels. A call topreventDefault()inside a passive listener is ignored. A listener that wants to cancel must be registered with{ passive: false }. - Capture and bubble phases: an event first travels down from
windowto the target (capture phase), then back up towindow(bubble phase). A listener is on the bubble side unless registered with{ capture: true }. touch-action: a CSS property that tells the browser which touch gestures it may handle itself.autoleaves everything to the browser,nonelets it handle no gesture, andpan-ylets it handle only vertical panning, so horizontal drags are left to the page.pointercancel: an event the browser sends when it takes a gesture over (for example to scroll the page), after which the page gets no more pointer events for that touch.- Scroller: the nearest ancestor that scrolls, here the carousel
div.
The table is in the order a reproduction usually goes: one reload with the probe from Step 2 answers the first row, and a clean probe moves you to the second and third.
| Cause | Check | Tell-tale |
|---|---|---|
A listener calls preventDefault() on a touch event (touchstart / touchmove) | instrumentation below | log shows the call |
CSS touch-action on the touched element or an ancestor up to the scroller excludes the gesture | Elements panel, Computed tab, filter touch-action, walk up the ancestors | no preventDefault logged, gesture still dead |
| Another element is on top, or the browser started a different gesture (page scroll, back-swipe, pull to refresh) | document.elementFromPoint(x, y) at the touch point, and the Event Listener Breakpoints below | touch events never reach the carousel |
In plain terms: a touch-action that forbids panning on any element between the finger and the scroller wins, and no JavaScript is involved. This matters because touch-action is intersected from the touched element up to the scrolling element (MDN: "the browser intersects the touch-action values of the touched element and its ancestors", up to the first containing scrolling element), so a touch-action: none on the scroller or on any element between it and the touched element kills horizontal panning with nothing to find in any handler. For pointer events, MDN says an application declares which gestures the browser handles with touch-action, and receives pointercancel when the browser takes the gesture over; for touch events, the classic way to stop native panning is preventDefault() on touchstart or touchmove from a non-passive listener.
Step 2: instrument preventDefault
Install this early (a snippet in DevTools "Sources > Snippets" or an init script in a test; in a normal page load put it first in <head>). It does not change behaviour, it only records. Each preventDefault() call looks the method up on Event.prototype at the moment of the call, so the patch also catches listeners that were registered before it was installed; it misses calls made through a reference a script saved earlier (const pd = Event.prototype.preventDefault) and gestures that finished before the patch ran.
const probe = () => {
window.__cancels = [];
const orig = Event.prototype.preventDefault;
Event.prototype.preventDefault = function () {
if (this.cancelable && /^(touch|pointer)/.test(this.type)) {
const frames = new Error().stack.split('\n').filter(l => l !== 'Error').slice(1, 3).map(s => s.trim().replace(/\(.*[\\/]/, '('));
window.__cancels.push({ type: this.type, target: this.target.id || this.target.className, frames });
}
return orig.call(this);
};
};
What the probe does, line by line:
window.__cancels = []is the log the page keeps.Event.prototypeholds the methods every event object shares, so replacingpreventDefaultthere intercepts calls from every file.- The replacement acts only when the event
cancelable(a non-cancelable event cannot be stopped anyway) and itstypestarts withtouchorpointer. new Error().stackis a multi-line string of the current call stack. Chromium starts it with anErrorheader line; Firefox and Safari do not, sofilter(l => l !== 'Error')drops the header where it exists. The first remaining line is the replacement function itself, the next is the function that calledpreventDefault()(the culprit), and the one after is whoever called that.slice(1, 3)keeps those last two. Frame text differs by engine (Chromiumat HTMLDivElement.trackDrag (http://app.test/:10:57), Firefox and WebKittrackDrag@http://app.test/:10:57, with their own line and column numbers), but in a run of this probe in Chromium, Firefox and WebKit the culprit was the first of the two kept frames in each..replace(/\(.*[\\/]/, '(')shortens Chromium's parenthesised frames by removing the folder or URL part, leaving the function, line and column. Firefox and WebKit frames have no parentheses, so they keep the full URL; the function name is still first.orig.call(this)runs the realpreventDefault, so the page behaves as before.
Interactive tricks that need no code change:
- Event Listener Breakpoints (a DevTools Sources panel sidebar that pauses the page whenever a chosen event type fires; Touch >
touchmove, Pointer >pointermove): execution pauses in each listener, and you step to thepreventDefault()call. getEventListeners(element)in the Chromium DevTools console (Firefox shows an event badge on the element in the Inspector instead) lists the listeners on one element, with each listener'spassiveflag and function, which you can open in the Sources panel. Run it on the touched element and on each ancestor.- Bracket the cancel point. Log
event.defaultPreventedfrom a capture-phase listener onwindow({ capture: true }, runs before every other listener on the path) and from a bubble-phase listener onwindow(runs after them). If it isfalsethentrue, a handler on the path between the target andwindowcancelled it. For example, if the two loggers were added to the carousel page in Step 3, the capture logger onwindowprintsfalse(no other listener has run yet),trackDragon the carousel callspreventDefault(), and the bubble logger onwindowprintstrue, so the culprit sits on the path from the touched slide up towindow. - Search patterns in the code base:
preventDefault,passive: false(a listener registered onwindow,documentorbodyfortouchstartortouchmoveis passive by default, so it can only cancel if it sayspassive: false),touch-action, andstopPropagation/stopImmediatePropagation(a handler might not cancel anything itself but prevent the carousel from seeing the events).
Step 3: reproduce and read the answer
The harness builds a horizontal carousel (a scrolling div) plus a far-away script that cancels every one-finger touchmove on it. It swipes with real touch events through the Chrome DevTools Protocol (CDP, the debugging API that Chromium exposes and Playwright uses, Chromium only) in three variants: the culprit listener, touch-action: none set on the carousel itself (with the culprit script removed) and a clean page. It waits for the condition rather than a fixed delay, and exits non-zero if any variant misbehaves.
// find-prevent-default.mjs
import { chromium } from 'playwright';
// A horizontally scrolling carousel. One unrelated component registers a non-passive touchmove
// listener that cancels the gesture.
const html = `<style>
body{margin:0}
#carousel{width:300px;height:100px;overflow-x:auto;overflow-y:hidden;white-space:nowrap}
#carousel .slide{display:inline-block;width:300px;height:100px}
</style>
<div id="carousel"><div class="slide">1</div><div class="slide">2</div><div class="slide">3</div></div>
<div id="drag-handle" style="height:50px">drag-handle</div>
<script>
// The culprit, registered far from the carousel code.
function trackDrag(e) { if (e.touches.length === 1) e.preventDefault(); }
document.getElementById('carousel').addEventListener('touchmove', trackDrag, { passive: false });
</script>`;
// Injected before any page script runs: log who cancels what.
const probe = () => {
window.__cancels = [];
const orig = Event.prototype.preventDefault;
Event.prototype.preventDefault = function () {
if (this.cancelable && /^(touch|pointer)/.test(this.type)) {
const frames = new Error().stack.split('\n').filter(l => l !== 'Error').slice(1, 3).map(s => s.trim().replace(/\(.*[\\/]/, '('));
window.__cancels.push({ type: this.type, target: this.target.id || this.target.className, frames });
}
return orig.call(this);
};
};
const swipe = async (cdp, page) => {
const pt = (x) => [{ x, y: 50 }];
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: pt(250) });
for (let x = 240; x >= 60; x -= 20) await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: pt(x) });
await cdp.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });
};
const b = await chromium.launch();
const ctx = await b.newContext({ hasTouch: true, viewport: { width: 300, height: 200 } });
for (const variant of ['listener', 'touch-action', 'clean']) {
const withCulprit = variant === 'listener';
const page = await ctx.newPage();
await page.addInitScript(probe);
let body = withCulprit ? html : html.replace(/<script>[\s\S]*<\/script>/, '');
if (variant === 'touch-action') body = body.replace('#carousel{', '#carousel{touch-action:none;');
await page.route('http://app.test/', route => route.fulfill({ contentType: 'text/html', body }));
await page.goto('http://app.test/');
const cdp = await ctx.newCDPSession(page);
await swipe(cdp, page);
if (variant === 'clean') await page.waitForFunction(() => document.getElementById('carousel').scrollLeft > 0);
await page.evaluate(() => new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))));
const r = await page.evaluate(() => ({ scrolled: document.getElementById('carousel').scrollLeft > 0, cancelled: window.__cancels.length > 0, culprit: window.__cancels[0]?.frames[0] ?? null }));
console.log(variant.padEnd(12), JSON.stringify(r));
if (withCulprit && (r.scrolled || !r.cancelled)) { console.log('FAIL'); process.exitCode = 1; }
if (variant === 'clean' && (!r.scrolled || r.cancelled)) { console.log('FAIL'); process.exitCode = 1; }
if (variant === 'touch-action' && (r.scrolled || r.cancelled)) { console.log('FAIL'); process.exitCode = 1; }
await page.close();
}
await b.close();
Run in the Playwright 1.48.2 image (Chromium only, because the DevTools Protocol touch injection used here is a Chromium feature), it prints:
listener {"scrolled":false,"cancelled":true,"culprit":"at HTMLDivElement.trackDrag (:10:57)"}
touch-action {"scrolled":false,"cancelled":false,"culprit":null}
clean {"scrolled":true,"cancelled":false,"culprit":null}
Reading it: the first line scrolls nothing and the probe names trackDrag. In at HTMLDivElement.trackDrag (:10:57), HTMLDivElement is the object the listener was called on (the carousel), trackDrag is the function that called preventDefault(), and :10:57 is line 10, column 57 of the page's HTML (the served document, not a separate file): the preventDefault call inside trackDrag. The file part is empty because the probe's regex stripped the page URL; in a bundled app the stack gives the file and function. The second line (touch-action: none on the carousel) scrolls nothing and cancelled nothing, so the culprit is CSS, not script: go to the Computed touch-action. The third line is the baseline: the same swipe scrolls.
Step 4: fix and keep it fixed
- Cancel only when you own the gesture: decide in
touchstart/pointerdown(or by the angle of the first move) that the drag is vertical, and only then callpreventDefault(); otherwise return without calling it. - Prefer
touch-action: pan-yon the draggable element to tell the browser up front that only vertical panning is its job and horizontal movement is yours, instead of cancelling events one by one. MDN notes that applications should usetouch-action"to ensure the browser knows the intent of the application before any event listeners have been invoked". - Remove
{ passive: false }where the handler does not need to cancel. - Keep a regression test like the harness above, and a code-review/lint check for new
preventDefault()calls in touch handlers.
Running the code
echo '{"type":"module"}' > package.json
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c 'npm i --no-audit --no-fund playwright@1.48.2 && node find-prevent-default.mjs'
This component renders {items.length && <List items={items} />} and the page shows a stray 0 whenever the list is empty. Explain why it happens and describe the conditional rendering approaches you would use in JSX and when each is the right choice.
Sample Answer
Direct answer
items.length && <List /> is a JavaScript expression before it is JSX. The && operator returns its left operand when that operand is falsy (a value that counts as false in a condition: false, 0, -0, 0n, '', null, undefined and NaN; everything else is truthy), so with an empty array the expression evaluates to the number 0, and React renders numbers as text. The run below shows that React renders nothing for false, null and undefined, but 0 is a number, so a stray 0 appears. The fix is to make the left side a real boolean (items.length > 0 && ...), or to pick another conditional pattern from the list below.
What React renders for each left operand
The run below renders <div>{v && <b>shown</b>}</div> to a static HTML string (renderToStaticMarkup from react-dom/server turns an element into its markup text without attaching it to a page) for several values of v:
{
"0": "<div>0</div>",
"1": "<div><b>shown</b></div>",
"NaN": "<div>NaN</div>",
"''": "<div></div>",
"false": "<div></div>",
"null": "<div></div>",
"undefined": "<div></div>",
"'0'": "<div><b>shown</b></div>"
}
Three results are worth noticing. 0 and NaN leak into the page. (React 18 also logs a console warning for NaN that starts with "Received NaN for the", but still renders it.) The empty string '' is falsy, is returned by &&, and renders as nothing, so it hides the bug if the left side is a string. And the string '0' is truthy (any non-empty string is), so it takes the right-hand branch. The rule: with &&, the left side must be a boolean, or a value whose falsy cases you are happy to render. A count, a length, a price or an index is a number, so it needs a comparison.
The conditional patterns and when to use each
The code numbers the patterns the same way as the explanation after it: pattern 1 is && (shown as the bug in 1a and the fix in 1b), then 2 ternary, 3 early return, 4 wrapper component, 5 higher-order component, 6 render prop. Patterns 1 to 3 are what most components need; patterns 5 and 6 were the standard ways to share behaviour before hooks arrived in React 16.8, and today a custom hook or a plain wrapper usually does the same job, so they mostly appear in existing code.
export const List = ({ items }) => <ul>{items.map((i) => <li key={i}>{i}</li>)}</ul>;
// 1a. Logical AND on a number (the bug)
export const AndBug = ({ items }) => <div>{items.length && <List items={items} />}</div>;
// 1b. Logical AND on a real boolean
export const AndFixed = ({ items }) => <div>{items.length > 0 && <List items={items} />}</div>;
// 2. Ternary: two different outcomes
export const Ternary = ({ items }) => (
<div>{items.length > 0 ? <List items={items} /> : <p>Nothing here yet</p>}</div>
);
// 3. Early return: the whole component bails out
export function EarlyReturn({ items }) {
if (items.length === 0) return <p>Nothing here yet</p>;
return <List items={items} />;
}
// 4. Wrapper component that gates its children
export const When = ({ if: cond, fallback = null, children }) => (cond ? children : fallback);
export const Gated = ({ items }) => (
<When if={items.length > 0} fallback={<p>Nothing here yet</p>}><List items={items} /></When>
);
// 5. Higher-order component (a function that takes a component and returns a gated one)
export const hideWhenEmpty = (Component) => (props) => (props.items.length > 0 ? <Component {...props} /> : null);
export const HiddenList = hideWhenEmpty(List);
// 6. Render prop: the data component decides, the caller supplies the markup
export const WithItems = ({ items, children }) => (items.length > 0 ? children(items) : null);
cond && <X />(with a booleancond): the shortest form, right when "nothing" is the correct empty output. Useitems.length > 0,Boolean(x)or!!x(both turn any value intotrueorfalse). The operator short-circuits: when the left side is falsy, the right side is never evaluated.- Ternary
cond ? <A /> : <B />: right when both outcomes render something, such as the list or an empty-state message. It is also safe against the0problem because the result is whichever branch you wrote. Avoid nesting ternaries; extract a component. - Early return (
if (...) return <Empty />): right when the whole component has nothing to show, because it keeps the main path unindented. Put it after all hook calls. - A gating wrapper component (
<When if={...} fallback={...}>): right when several places repeat the same condition and fallback. This is the plain form of what a higher-order component or a render prop does. - A higher-order component (HOC) such as
hideWhenEmpty(List): a function that takes a component and returns a gated one. It suits behaviour shared across many components, but it hides the condition inside a wrapper, so prefer a plain wrapper or a hook unless many components need the same gate. - A render prop (
<WithItems>{(items) => ...}</WithItems>): a component receives a function aschildrenand calls it only when there is data; right when the data owner decides when to render and the caller owns the markup.
Proof
import { renderToStaticMarkup } from 'react-dom/server';
import { render } from '@testing-library/react';
import { AndBug, AndFixed, Ternary, EarlyReturn, Gated, WithItems, HiddenList, List } from './conditional.jsx';
const html = (el) => renderToStaticMarkup(el);
const filled = ['a', 'b'];
test('what each value of the left operand renders when it is the whole && expression', () => {
const row = (v) => html(<div>{v && <b>shown</b>}</div>);
const got = {
'0': row(0), 'NaN': row(NaN), "''": row(''), 'false': row(false),
'null': row(null), 'undefined': row(undefined), '1': row(1), "'0'": row('0'),
};
console.log(JSON.stringify(got, null, 1));
expect(got['0']).toBe('<div>0</div>');
expect(got['NaN']).toBe('<div>NaN</div>');
expect(got["''"]).toBe('<div></div>');
expect(got['false']).toBe('<div></div>');
expect(got['null']).toBe('<div></div>');
expect(got['undefined']).toBe('<div></div>');
expect(got['1']).toBe('<div><b>shown</b></div>');
expect(got["'0'"]).toBe('<div><b>shown</b></div>');
});
test('the bug: an empty array renders a literal 0', () => {
expect(html(<AndBug items={[]} />)).toBe('<div>0</div>');
expect(html(<AndBug items={filled} />)).toBe('<div><ul><li>a</li><li>b</li></ul></div>');
});
test('every fix renders no stray 0 and the same list when there are items', () => {
const list = '<ul><li>a</li><li>b</li></ul>';
expect(html(<AndFixed items={[]} />)).toBe('<div></div>');
expect(html(<AndFixed items={filled} />)).toBe(`<div>${list}</div>`);
expect(html(<Ternary items={[]} />)).toBe('<div><p>Nothing here yet</p></div>');
expect(html(<Ternary items={filled} />)).toBe(`<div>${list}</div>`);
expect(html(<EarlyReturn items={[]} />)).toBe('<p>Nothing here yet</p>');
expect(html(<EarlyReturn items={filled} />)).toBe(list);
expect(html(<Gated items={[]} />)).toBe('<p>Nothing here yet</p>');
expect(html(<Gated items={filled} />)).toBe(list);
expect(html(<HiddenList items={[]} />)).toBe('');
expect(html(<HiddenList items={filled} />)).toBe(list);
expect(html(<WithItems items={[]}>{(i) => <List items={i} />}</WithItems>)).toBe('');
expect(html(<WithItems items={filled}>{(i) => <List items={i} />}</WithItems>)).toBe(list);
});
test('the && version also updates correctly in the DOM when the list empties', () => {
const { container, rerender } = render(<AndBug items={filled} />);
expect(container.textContent).toBe('ab');
rerender(<AndBug items={[]} />);
expect(container.textContent).toBe('0');
});
test('&& short-circuits: the right-hand side is not evaluated when the left is falsy', () => {
let evaluated = 0;
const heavy = () => { evaluated += 1; return <b>x</b>; };
html(<div>{false && heavy()}</div>);
expect(evaluated).toBe(0);
html(<div>{true && heavy()}</div>);
expect(evaluated).toBe(1);
});
Run with the setup below and the command npx vitest run cond --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion' (the grep keeps only the result lines; the first test also prints the JSON table shown earlier), the result lines are:
✓ cond/conditional.test.jsx > what each value of the left operand renders when it is the whole && expression
✓ cond/conditional.test.jsx > the bug: an empty array renders a literal 0
✓ cond/conditional.test.jsx > every fix renders no stray 0 and the same list when there are items
✓ cond/conditional.test.jsx > the && version also updates correctly in the DOM when the list empties
✓ cond/conditional.test.jsx > && short-circuits: the right-hand side is not evaluated when the left is falsy
Tests 5 passed (5)
The tests assert the exact markup for the bug (<div>0</div>), for each fix with an empty and a non-empty array, for the DOM update when a list empties, and for && short-circuiting. A mutation check temporarily breaks the real code and confirms a test notices: changing the fixed component back to items.length && (sed -i 's/items.length > 0 \&\& <List/items.length \&\& <List/' cond/conditional.jsx) fails the fix test:
✓ cond/conditional.test.jsx > what each value of the left operand renders when it is the whole && expression
✓ cond/conditional.test.jsx > the bug: an empty array renders a literal 0
× cond/conditional.test.jsx > every fix renders no stray 0 and the same list when there are items
✓ cond/conditional.test.jsx > the && version also updates correctly in the DOM when the list empties
✓ cond/conditional.test.jsx > && short-circuits: the right-hand side is not evaluated when the left is falsy
⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯
AssertionError: expected '<div>0</div>' to be '<div></div>' // Object.is equality
Tests 1 failed | 4 passed (5)
Pitfalls
- Rendering
0is sometimes wanted. A cart count of 0 may need to show "0 items". Then use a ternary and write the zero case on purpose. - Missing data. If
itemscan beundefinedwhile loading,items.lengththrows. Use a loading branch first (if (!items) return <Spinner />) rather thanitems?.length, which turns "not loaded" into "empty" and flashes the wrong message. - Hooks order. An early return placed before a hook call changes the number of hooks between renders. Put early returns after all hooks.
- Nested
&&chains read as logic puzzles; name the condition (const hasResults = items.length > 0) first.
Running the code
npm init -y && npm pkg set type=module # files go in demo/cond/
npm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16.0.1 @testing-library/dom@10.4.0 jsdom@25.0.1 vitest@2.1.4
# vitest.config.js:
# import { defineConfig } from 'vitest/config';
# export default defineConfig({ esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom', globals: true } });
npx vitest run cond --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion'
Run in a node:22 container (Node 22.23.3).
Define the term 'edge case' (and 'corner case') in the context of software testing. Why does systematically identifying them matter more than testing only the happy path? Give at least eight concrete categories, spanning at least three different domains (a generic input-validation example, a production/reliability example, and a data or ML-pipeline example).
Sample Answer
Direct answer
An edge case (or corner case, when two or more boundary conditions intersect) is an input, state, or condition at the extreme or unusual end of what a system is expected to handle, distinct from the 'happy path' of typical, well-formed usage; systematically identifying them matters because production traffic and adversarial users reliably generate exactly these unusual conditions, while happy-path testing alone only proves the system works when everything goes as expected, which is rarely where real defects live.
Structured elaboration: eight categories, spanning multiple domains
- Empty/null: an empty list, a null field, a zero-length string. Example (general software): a search function called with an empty query string.
- Boundary/max-min: values exactly at, or one step past, a defined limit. Example (backend): a pagination
page_sizeparameter at exactly the server-enforced maximum. - Zero/negative: values a numeric field technically accepts as a type but that may be nonsensical for the domain. Example (SRE/production): a negative value in a counter that should only ever increase, signaling either overflow or a bug in the decrement logic.
- Duplicate: repeated values where uniqueness might be silently assumed. Example (general software): two items with the same ID in a list a system expects to be de-duplicated upstream.
- Malformed/invalid type: input that is the wrong shape or type entirely. Example (backend): a JSON field expected to be an integer arriving as a string or an array.
- Out-of-order/concurrent: events or requests arriving in an unexpected sequence, or overlapping in time. Example (SRE/production): a delivery-confirmation event for a message arriving before the message-sent event, due to network reordering.
- Very large/very small scale: inputs at a magnitude far outside typical testing. Example (data/ML pipeline): a categorical feature with hundreds of millions of unique values (e.g. a raw user ID) fed into a one-hot encoder, which can silently exhaust memory.
- Environment/locale-specific: behavior that only manifests under a specific timezone, locale, or platform. Example (general software): a date-parsing function that behaves correctly in the US locale but misinterprets day/month order elsewhere.
Worked example: why happy-path testing alone misses these
A login form tested only with a valid, well-formed email and a correct password will pass every happy-path test while shipping with a null-pointer crash on an empty password field, an infinite spinner on a 10,000-character email, or a silent security bypass on a SQL-injection-shaped username, none of which a happy-path suite would ever exercise, because by construction happy-path tests only feed the system inputs the developer already expected to work.
Trade-offs & pitfalls
Treating 'edge case' as synonymous with 'rare' is a common misconception: an empty list or a zero value is often one of the MOST common real-world inputs (a brand-new user's empty cart, a freshly-created account with no activity yet), not a rare corner case, which is exactly why the empty/null category above is listed first, not last; conflating 'edge case' with 'unlikely' leads teams to systematically under-test the cases that actually occur most often in a real user base's earliest interactions with a feature.
A company wants to roll out a new cross-functional process across product, engineering, support, and sales, but adoption is uneven and some teams are reverting to their old habits. How would you structure the rollout, identify where resistance is coming from, and decide whether the process needs to change?
Sample Answer
I would treat this as a change-management problem, not just a rollout problem.
First, I would diagnose where adoption is breaking down. I would review usage data, interview a few people from each function, and compare the new process to the old one. I want to know whether people are resisting because the process is too slow, unclear, misaligned with incentives, or simply not useful in their day-to-day work.
Then I would test the rollout design. I would ask: did we train people, give them a reason to care, and remove the old path? For example, if support keeps using the old escalation template, maybe the new process adds friction and does not solve their problem fast enough.
If the issue is execution, I would tighten enablement, add team champions, and publish a clear operating cadence. If the issue is the process itself, I would change it based on the feedback rather than forcing adoption of a bad design.
I would judge success by outcomes, not attendance at meetings. If adoption improves, cycle time drops, and fewer teams revert to the old habit, the rollout is working. If not, I would change the process before asking for more compliance.
For example, when a company rolled out a new cross-functional incident-escalation process across product, engineering, and support, usage data after three weeks showed only 40% of support tickets were being routed through the new template, the rest were still going through the old one. Interviews with five support agents revealed the real problem: the new template required them to fill in a business-impact field that only engineering had the context to answer, so agents defaulted back to the old, faster template rather than get stuck. That pointed to a process-design gap, not a training gap. The fix was to move the business-impact classification to a follow-up step engineering completed after triage, instead of asking support to guess it up front. Within two weeks of that change, template usage rose to 92%, and average escalation cycle time (the time from a ticket being flagged to a fix being assigned) dropped from about 3.5 days to just under 2 days.
Explain how you balance shipping quickly to learn versus ensuring product quality when requirements are ambiguous. List principles you use, decision criteria, and provide specific guardrails (for example: canary releases, feature flags, SLAs, error budgets) that let you move fast while managing customer risk.
Sample Answer
Direct answer
Decouple "shipped" from "fully rolled out": you can move fast on ambiguous requirements as long as
you control the blast radius of being wrong, using guardrails you build in before you ship, not
after an incident. The guardrails to know here are feature flags, canary releases, service level
agreements (SLAs), and error budgets, and together they turn "quality versus speed" from a values
argument into a number everyone already agreed to ahead of time.
Structured elaboration
Principles:
- Shipping code to production and exposing it to all your users are two separate decisions with
two separate risk levels; you can do the first quickly while staying deliberate about the
second. - Invest in the guardrails before you ship something ambiguous, not after it breaks. A guardrail
retrofitted post-incident is a lesson learned the expensive way. - Define, in numbers, what "good enough to learn from" means for this specific feature, since
ambiguous requirements otherwise leave "quality bar" floating and arguable after the fact. - Not all risk is equal: a bug in an internal dashboard shipped fast to learn is a different risk
class than a bug in a payment flow, and the guardrails you use should scale with which one
you're touching.
Decision criteria: think in two dimensions, reversibility and blast radius. Low blast radius
and easily reversible: ship fast behind a flag and learn from real usage. High blast radius or hard
to reverse (a schema migration, a pricing change, anything touching money, safety, or compliance):
slow down and add more upfront validation, regardless of deadline pressure, because ambiguous
requirements are not a good enough reason to accept irreversible risk.
Guardrails, and what each one actually is:
- Feature flag: a runtime on/off switch for a piece of code, letting you turn a feature off
instantly without a new deployment, and expose it to a specific subset of users first instead of
everyone at once. - Canary release: rolling a change out to a small slice of traffic or users first (commonly 1
to 5%) and watching key metrics before expanding further, so a bad change only affects a small
group before you find out. - SLA (service level agreement): a stated commitment about how reliable or fast a service will
be, for example 99.9% uptime or sub-300-millisecond response time, often with a real consequence
attached if missed, that sets an outer bound you don't cross even while moving fast. - Error budget: the amount of unreliability you're explicitly allowed, on purpose, within a
given period, derived from your SLA. A 99.9% uptime SLA implies roughly 43 minutes of allowed
downtime per 30-day month (the math: 1 minus 0.999, times 30 days, times 24 hours, times 60
minutes, is about 43.2 minutes). While you're within that budget, you ship and experiment freely;
once it's burned, feature work pauses and the team fixes reliability first. This turns "should we
slow down" into a number both sides already agreed to, instead of a fresh argument every time.
Worked example: a notifications feature adjacent to payments, with ambiguous requirements on
exact trigger conditions. Ship it behind a flag to a 2% canary for one week, tracking opt-out rate
and error rate against the existing SLA and error budget. If this feature's error-budget
consumption stays under, say, 10% of the monthly budget, and opt-out rate stays under 5%, expand to
25%, then to everyone, over the next two weeks. If error-budget consumption spikes instead, the
flag kills the feature instantly with no redeploy needed, and the damage stays isolated to the 2%
cohort (basis: cohort-level error rate, not the whole user base).
Second, shorter example (different discipline): a marketing team piloting a new lifecycle
email sequence to 5% of the list before a full send is running the identical canary logic without
any code involved: bounded exposure, a pre-set metric (unsubscribe rate) to watch, and a defined
threshold before expanding to the full list.
Trade-offs and pitfalls
"Move fast and fix it later" with no guardrail works right up until "later" is a public incident.
The opposite mistake, blocking everything on a fully specified plan before shipping anything, just
recreates the slow, spec-first failure mode the question's premise (ambiguous requirements) is
explicitly asking you to work around, not wait out.
Someone you're mentoring keeps missing commitments and blames unclear requirements. Walk through how you'd figure out what's actually going on and what you'd do about it.
Sample Answer
Direct answer
"Unclear requirements" is a real cause sometimes and a convenient explanation other times, so the first job is figuring out which, using evidence rather than taking the explanation at face value. Look at the pattern across several instances, not just the latest miss, separate estimation problems from execution problems from actual requirement gaps, then fix the specific mechanism, not the person's attitude.
Diagnose using the pattern, not the excuse
- Pull several recent examples, not just the most recent miss. Was the requirement genuinely ambiguous every time, or does "unclear requirements" get invoked even when the ticket had clear acceptance criteria? The former is a process problem; the latter is a signal something else is going on (confidence, avoidance, poor estimation).
- Look for where in the workflow it breaks down: did they ask clarifying questions before starting and get bad answers, or did they not ask and guess? Did the requirement change mid-task without being re-scoped? Did they commit to something they didn't actually understand, to avoid looking behind?
Separate the possible root causes
- Genuine ambiguity: the requirement really was underspecified and nobody caught it before work started.
- Estimation or planning gap: the requirement was clear but the person didn't break it down enough to notice the ambiguous parts until they hit them.
- Avoidance: asking clarifying questions feels risky (looks like not knowing), so they guess and then have a ready explanation when it goes wrong.
- Skill gap under a different name: they may not yet have the judgment to know what "clear enough to start" looks like.
Fix the mechanism that matches the cause
- Genuine ambiguity: introduce a lightweight definition-of-ready check before work starts, owned jointly, not something you police alone.
- Estimation or planning: practice breaking a ticket into sub-tasks together and flag the ambiguous piece explicitly before committing to a date.
- Avoidance: make asking clarifying questions cheap and normal, model it yourself, and separate "I don't know yet" from an evaluation of competence.
- Skill gap: pair on a couple of tickets so they see what "clear enough" actually looks like in practice, rather than being told about it abstractly.
Worked example
A mentee on a team I supported kept missing sprint commitments, and the stated reason was always some version of unclear requirements. Looking at the last four tickets together, not just the most recent one, a pattern showed up: on three of the four, the acceptance criteria were actually written clearly, but the mentee hadn't asked any clarifying questions before starting, then hit an edge case mid-task and treated the whole ticket as ambiguous from the start. On the fourth, the ticket genuinely was underspecified.
The fix wasn't "communicate more clearly" in the abstract. It was two things: a short pre-work check where we'd both look at a ticket before it was picked up and flag anything genuinely unclear (catching the real ambiguity case), and a habit of the mentee sending one clarifying question per ticket before starting, even a small one, to break the avoidance pattern. The signal it was working wasn't a single metric; it was that "unclear requirements" stopped being the explanation for misses, because the real ambiguity was being caught earlier and the avoidance pattern had a lower-stakes outlet.
Trade-offs and pitfalls
- Taking "unclear requirements" at face value every time lets a deeper issue (avoidance, skill gap) hide behind a plausible-sounding excuse indefinitely.
- Assuming it's never true is just as wrong; requirements genuinely are underspecified sometimes, and treating every instance as a character problem erodes trust.
- The fix has to match the actual cause. A definition-of-ready checklist won't help someone avoiding asking questions, and coaching someone to "just ask more" won't help if the requirements really were bad.
A team that depends on you is expecting a delivery on a fixed date, but the team you depend on is running behind. How do you handle the sequencing conflict?
Sample Answer
Direct answer
Make the mismatch visible the moment you see it, whether that is after the upstream team is already running behind or as soon as it surfaces during planning itself, and look first for a way to decouple your own delivery from their exact finish order, such as a stub, an adapter, or a feature flag, so you have room to negotiate re-sequencing or reduced scope instead of just waiting to see if the date slips.
Structured elaboration
Surface the mismatch immediately, not once it is a crisis
Whether you discover it because the other team is visibly behind, or because it becomes obvious during a shared planning session, name it out loud right away: here is what we committed to, here is what we now depend on, here is the gap.
Look for a decoupling option before assuming you have to slip
A mock interface, a stubbed API, or a feature flag lets your work continue against a placeholder while the real dependency finishes in parallel, with a defined swap-in point once it is ready.
Negotiate re-sequencing with a concrete ask, not just a complaint
Pointing out that another team is behind invites defensiveness. Proposing a specific way both teams can still hit their dates if two pieces are resequenced invites problem-solving instead.
Communicate consistently to everyone downstream of the decision
Use the same explanation each time: what changed, what the new plan is, and what happens if it changes again.
Set escalation triggers before you need them
Agree upfront on the specific checkpoint, a date or a milestone, at which, if the upstream work still is not ready, the issue escalates automatically to both leads, rather than waiting for the final deadline to find out.
Worked example
Base case: discovered after the upstream team is already behind. A team is building a feature on top of a platform capability, and the platform team is now behind schedule on it. Rather than waiting to see if the platform team catches up, the team builds a lightweight adapter against a mocked version of the interface, so its own work continues. They set an explicit go or no-go checkpoint a week before their real deadline: if the real dependency is not ready by then, they ship against the mock with a manual fallback, and swap in the real dependency once it lands.
Planning-time discovery variant. During a multi-team sprint-planning session, it becomes clear in the room that one team's planned start date for a shared integration depends on another team's work, which is not scheduled to finish until after the first team's own committed date, a mismatch nobody had caught before that meeting. The engineer facilitating the session, in this scenario a DevOps engineer coordinating the shared infrastructure both teams touch, flags the conflict on the spot and proposes re-sequencing right there: the first team starts against a stubbed interface while the second team's work continues in parallel, with the real dependency swapped in once ready. Right after the session, the facilitator sends a short written summary to both team leads and stakeholders using a repeatable communication template: what was found, what was agreed, and what happens if either date slips again. The summary also sets an explicit escalation trigger: if the second team's work is not ready by a named checkpoint date, it escalates automatically to both leads instead of surfacing again only at the final deadline.
Trade-offs and pitfalls
Building a decoupling layer, such as an adapter, a mock, or a flag, costs real engineering time that is wasted if the upstream team finishes on schedule after all. It is worth it when the downside of waiting and being wrong is worse than the cost of building it and not needing it, which is usually true for anything on a hard external deadline.
Escalating too early, before giving the upstream team a real chance to communicate a plan, burns trust and can look like an attempt to shift blame preemptively. Escalating too late removes any options besides slipping the date. Pre-agreed, specific escalation triggers tied to a date rather than a feeling are what keep this from being a judgment call made under pressure.
A gallery page loads many images and thumbnails. When does it make sense to wait for every request, and when for only the first to answer? Give a concrete frontend case for each, and say what each approach does when one of the requests fails and what the user ends up seeing.
Sample Answer
Direct answer
Start here: ask what the screen needs. If it needs every result, wait for all of them; if one good answer is enough, take the first; if one failure must not spoil the rest, collect each outcome separately.
Wait for every request when the screen is only correct with all the results, and wait for the first when any one answer is enough. Concretely, a gallery's thumbnail grid needs every thumbnail, but a failure of one should not blank the rest, so use Promise.allSettled (wait for all, never short-circuit). A hero image that exists on three CDN mirrors (identical copies of the file on different content-delivery-network servers, so any one of them will do) needs only the first mirror that works, so use Promise.any (first success). The plain versions, Promise.all and Promise.race, both short-circuit on the first rejection (they settle immediately with that failure instead of waiting for the remaining inputs), so on a failing request they hand the user an error instead of a partial page. Use them only when that is the behaviour you want.
The four combinators
A promise combinator is a function that takes several promises and returns one promise built from their outcomes.
| Combinator | Resolves with | Rejects when | Failure leaves the other requests |
|---|---|---|---|
Promise.all | Array of all values, in input order | The first input rejects | Still running (nothing cancels them) |
Promise.allSettled | Array of {status, value} or {status, reason}, one per input | Never; it always waits for every input | Waited for |
Promise.race | The first input to settle, success or failure | The first settled input is a rejection | Still running |
Promise.any | The first input to fulfill | Every input rejected: an AggregateError whose errors array holds the reasons in input order | Still running after the first success |
(MDN documents the any semantics, the AggregateError, and that a result does not cancel the other operations.)
Each one on a gallery, with what the user sees
AggregateError is a built-in error type that bundles several errors into one: its errors array holds each underlying failure. The script uses fake loaders with fixed delays (20, 40, 60 ms etc.) so the outcomes are reproducible, and it prints each result. Reading the helpers: load(url, ms, fail, signal) returns a promise that settles after ms milliseconds, resolving with the url or rejecting, and it also rejects early if the optional signal (an AbortSignal, the cancellation token an AbortController hands out) fires. show(label, p) waits for p, then prints the label padded to 22 characters followed by either the JSON of the result or the error's name and message; for an AggregateError it joins the messages from e.errors. Each await show(...) line below therefore matches one line of the output.
// Fake image loader: resolves with the url after `ms`, or rejects if `fail` is true.
const load = (url, ms, fail = false, signal) => new Promise((resolve, reject) => {
const t = setTimeout(() => (fail ? reject(new Error(url + ' failed')) : resolve(url)), ms);
signal?.addEventListener('abort', () => { clearTimeout(t); reject(signal.reason); });
});
const show = async (label, p) => console.log(label.padEnd(22), await p.then((v) => JSON.stringify(v), (e) => e.name + ': ' + (e.errors ? e.errors.map((x) => x.message).join(', ') : e.message)));
const thumbs = () => [load('t1.jpg', 60), load('t2.jpg', 20, true), load('t3.jpg', 40)];
await show('all (one fails)', Promise.all(thumbs()));
await show('allSettled', Promise.allSettled(thumbs()).then((rs) => rs.map((r) => r.status === 'fulfilled' ? r.value : 'rejected: ' + r.reason.message)));
await show('any (mirrors)', Promise.any([load('cdn-a/hero.jpg', 50, true), load('cdn-b/hero.jpg', 80), load('cdn-c/hero.jpg', 30, true)]));
await show('any (all fail)', Promise.any([load('a', 10, true), load('b', 20, true)]));
await show('race (fast failure)', Promise.race([load('slow-ok', 60), load('fast-fail', 10, true)]));
// race as a timeout: the losing request keeps running unless it is aborted
let finished = false;
const slow = new Promise((r) => setTimeout(() => { finished = true; r('slow body'); }, 80));
const timeout = (ms) => new Promise((_, rej) => setTimeout(() => rej(new Error('timed out')), ms));
await show('race timeout', Promise.race([slow, timeout(20)]));
console.log('slow request still ran to completion:', await new Promise((r) => setTimeout(() => r(finished), 120)));
let abortedRan = false;
const ac = new AbortController();
const abortable = new Promise((resolve, reject) => {
const t = setTimeout(() => { abortedRan = true; resolve('slow body'); }, 80);
ac.signal.addEventListener('abort', () => { clearTimeout(t); reject(ac.signal.reason); });
});
const timer = setTimeout(() => ac.abort(new Error('aborted by caller')), 20);
await show('race with abort', abortable.finally(() => clearTimeout(timer)));
console.log('aborted request ran to completion:', await new Promise((r) => setTimeout(() => r(abortedRan), 120)));
console.log('empty input: all ->', JSON.stringify(await Promise.all([])), '| any ->', await Promise.any([]).catch((e) => e.name));
Run in a Node 22 container, it prints:
all (one fails) Error: t2.jpg failed
allSettled ["t1.jpg","rejected: t2.jpg failed","t3.jpg"]
any (mirrors) "cdn-b/hero.jpg"
any (all fail) AggregateError: a failed, b failed
race (fast failure) Error: fast-fail failed
race timeout Error: timed out
slow request still ran to completion: true
race with abort Error: aborted by caller
aborted request ran to completion: false
empty input: all -> [] | any -> AggregateError
allwith one failing thumbnail rejects witht2.jpg failedand the other two successful results are thrown away. The user sees an error state for the whole gallery. Right when the page cannot render without every piece (for example a checkout page needing both cart and prices).allSettledreturns all three outcomes. The gallery renders two thumbnails and one placeholder with a retry button. This is the right default for independent tiles.anyover mirrors resolved withcdn-b/hero.jpg, the first to succeed, ignoring the two failures. If every mirror fails you get anAggregateError(shown on theany (all fail)line) and should render the fallback image. Right for redundant sources of the same thing.racewith a fast failure rejects with the failure even though a slower request would have succeeded. Right for "first answer of any kind", rarely for images.raceas a timeout is the common use: race the request against a timer that rejects. The output shows the pitfall:slow request still ran to completion: true. The loser keeps running, using bandwidth and possibly updating state later.- Fix: give the request an
AbortController(a browser and Node API for cancelling work); on timeout callabort()and the request is torn down. Therace with abortlines show the aborted request never completed (false). Withfetchyou pass{ signal }in the options; the request then rejects once aborted. - Empty input behaves differently:
Promise.all([])resolves with[], whilePromise.any([])rejects with anAggregateError. A gallery with zero images must not be treated as a failure.
Recommendation
Thumbnails: allSettled, render fulfilled ones, placeholders for rejected ones, one retry per tile. Hero image: any over the mirrors with an AbortController per request so the losers are cancelled once one wins. Page data that the screen needs in full: all, with a single error state. Timeouts: race against a timer, but always with abort() on the loser.
Pitfalls
- Using
allfor independent tiles and then wondering why one 404 blanks the page. - Reading the
allSettledarray as values: each entry is an object; checkstatusfirst. - Assuming
raceoranycancel the losers. They do not. - Unbounded fan-out (starting many requests at the same moment): firing hundreds of requests at once wastes bandwidth and competes with more important requests; cap concurrency when the count is large.
Two senior frontend engineers disagree about a team-wide approach to component composition and mentoring juniors. You are the technical lead. Describe how you would resolve the conflict, ensure juniors get consistent guidance, and incorporate the best parts of both viewpoints into a teachable standard and onboarding materials. Include concrete examples and measurable outcomes where relevant.
Sample Answer
Situation & goal
Two senior frontend engineers disagree on component composition (e.g., container-presentational vs. hooks-driven composition) and how juniors should be mentored. As technical lead I need to resolve conflict, create consistent guidance for juniors, and capture best of both views into a teachable standard and onboarding materials.
Action plan
- Facilitate a focused, timeboxed design discussion
- Ask each senior to present pros/cons with concrete examples (small demo repo or 10–15 minute walkthrough).
- Capture trade-offs: reusability, testability, bundle size, mental model for juniors.
- Align on objective criteria
- Define measurable decision factors: bundle impact (< +2 KB), average unit test coverage (> 80%), render performance (no noticeable jank in 95th percentile), and developer onboarding time.
- Prototype and measure
- Implement two small sample components (one for each approach) in a feature branch with docs and tests.
- Run simple metrics: bundle size (webpack), test coverage, and a quick dev survey (5 devs including 2 juniors) for understandability.
- Synthesize a hybrid standard
- Keep strengths from both approaches (e.g., use hook-based composition for shared logic + explicit presentational props for clarity).
- Produce a concise pattern guide: when to use hooks, when to split container/presentational, naming conventions, prop vs. context rules.
- Make it teachable and enforceable
- Create onboarding materials: checklist, example repo, 1-hour recorded walkthrough, and a 2-week mentor pairing plan.
- Add PR template and linter/ESLint rules to catch anti-patterns.
- Coaching & feedback loop
- Pair juniors with alternating mentors from both seniors for first 2 sprints.
- Run weekly office hours and monthly retro to adjust the standard.
Concrete example
- Standard: "Use hooks for local logic and reusable behavior; split purely presentational component when markup > 50 lines or props > 6."
- Onboarding: 1-hour workshop + 3 guided PRs in first sprint.
Measurable outcomes
- Reduce onboarding time by 30% (measured by time to first approved component PR).
- Achieve 90% adherence in first 8 weeks (via automated lint + quarterly audits).
- Increase junior confidence (pre/post survey) by 40%.
Result & learning
This approach resolves the conflict through evidence, yields a practical hybrid standard, ensures juniors receive consistent, measurable guidance, and keeps both seniors engaged by adopting their best ideas.
Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Frontend Developer jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs