Airbnb Frontend Developer (Entry Level) - Comprehensive Interview Preparation Guide
Airbnb's frontend interview process for entry-level candidates consists of a recruiter screening, an online technical assessment, and a full-day virtual onsite known as the 'Engineering Loop' with four structured rounds evaluating coding fundamentals, system design thinking, code quality practices, and cultural fit. The process emphasizes practical frontend skills, real-world problem-solving, and alignment with Airbnb's core values of belonging and design excellence.
Interview Rounds
Recruiter Screening
What to Expect
Initial phone call with a recruiter to assess basic fit, motivation, and background. This is a non-technical conversation focused on understanding your career goals, interest in Airbnb, relevant experience (even if limited for entry-level), and logistical details. The recruiter will also share information about the role, team, and upcoming interview stages. For entry-level candidates, this is an opportunity to demonstrate enthusiasm for learning and alignment with Airbnb's values.
Tips & Advice
Research Airbnb's mission and culture beforehand. Prepare 2-3 specific reasons why you want to work there (beyond salary). Practice a concise 1-2 minute pitch about yourself focusing on relevant projects or learning experiences. Have questions ready about the team and role. Be authentic—entry-level candidates are expected to be learning-focused rather than experts. Follow up promptly and maintain professionalism in all communications.
Focus Topics
Airbnb Belonging and Values Alignment
Understanding and articulating how Airbnb's core value of 'belong anywhere' resonates with you, and how you contribute to inclusive, user-centric design thinking.
Practice Interview
Study Questions
Communication and Learning Mindset
Ability to explain technical concepts clearly, ask thoughtful questions, and demonstrate curiosity about how frontend development impacts user experience.
Practice Interview
Study Questions
Relevant Experience and Projects
Discussion of your academic projects, personal projects, internships, or bootcamp work that demonstrate frontend fundamentals, problem-solving, or design implementation skills.
Practice Interview
Study Questions
Motivation and Career Goals
Clear articulation of why you're interested in Airbnb as a company, why frontend development excites you, and what you hope to learn in this role.
Practice Interview
Study Questions
Online Technical Assessment
What to Expect
A timed assessment (90-120 minutes) featuring 2-3 algorithmic problems hosted on platforms like HackerRank. For entry-level frontend developers, problems focus on core data structures (arrays, trees, basic graphs) and fundamental algorithms (DFS, BFS, sorting, basic dynamic programming). Problems may be framed around real-world scenarios or API design patterns relevant to frontend development. The goal is to evaluate problem-solving ability, coding fundamentals, and comfort with algorithmic thinking—core competencies even for frontend roles.
Tips & Advice
Practice LeetCode-style problems at the 'Easy' to 'Medium' level focusing on arrays, strings, linked lists, trees, and basic DP. Write clean, readable code with comments. Test edge cases mentally before submitting. For entry-level, prioritize correctness and clarity over optimization. Read problems carefully—understand constraints and expected output precisely. If stuck, explain your approach verbally (if in a live setting) or write pseudocode. Time management is critical; spend 2-3 minutes understanding, 20-30 minutes coding, 5-10 minutes testing. Don't spend excessive time on one problem if you're struggling; move on and return if time permits.
Focus Topics
JavaScript Language Specifics
Writing solutions in JavaScript: array methods (.map, .filter, .reduce), object/Set/Map operations, string methods, and built-in functions. Understanding time and space complexity implications.
Practice Interview
Study Questions
Basic Dynamic Programming
Introduction to DP concepts: memoization, tabulation, recognizing overlapping subproblems. Classic problems like Fibonacci, coin change (basic variants), and simple path-counting problems.
Practice Interview
Study Questions
Trees and Graph Traversal
Understanding binary trees, BSTs, tree traversals (inorder, preorder, postorder), and basic graph concepts (DFS, BFS). Ability to traverse and manipulate tree structures.
Practice Interview
Study Questions
Array and String Manipulation
Fundamental operations: searching, sorting, two-pointer techniques, sliding windows, and common string algorithms (reverse, substring search, anagram detection).
Practice Interview
Study Questions
Problem-Solving and Code Organization
Breaking down complex problems into steps, writing pseudocode, testing edge cases (empty inputs, single elements, duplicates, boundary conditions), and writing clean, readable code with variable names that make sense.
Practice Interview
Study Questions
Onsite Round 1: Frontend Coding Interview
What to Expect
A live interview where you build a functional UI component or implement a feature from scratch using vanilla JavaScript (or a framework if specified). Examples include building an autocomplete component with API integration, a star-rating widget embedded in a form, an interactive dropdown menu, or a photo gallery with lazy loading. You'll be expected to code in a shared IDE, discuss your approach, handle edge cases, write clean code, and optimize for performance and accessibility. The interviewer may ask follow-up questions about responsiveness, accessibility, testability, or how the component would scale in a real application.
Tips & Advice
Clarify requirements before coding: What should the component do? What are edge cases? Discuss your approach and architecture before diving into code. Write vanilla JavaScript first to demonstrate fundamentals, even if you'd use React in production. Handle keyboard navigation and accessibility (ARIA labels, semantic HTML) from the start. Test interactivity: verify hover states, focus states, keyboard navigation, and mobile behavior. Ask about performance concerns: should we optimize for large lists? Cache? Lazy load? Write testable code with clear separation of concerns. Don't memorize solutions; understand the pattern and explain your thinking aloud. Interviewers value your problem-solving process more than perfect code.
Focus Topics
CSS Styling and Responsive Design
Writing clean CSS for component styling, using flexbox or grid for layout, media queries for responsive design, managing specificity, and ensuring components work across browsers and devices (mobile-first approach).
Practice Interview
Study Questions
Performance Optimization and Edge Cases
Optimizing component rendering (avoiding unnecessary reflows), handling async operations (API calls), managing memory leaks, testing edge cases (empty states, error states, invalid inputs), and discussing performance trade-offs.
Practice Interview
Study Questions
State Management and Data Binding
Managing component state (current input, selections, loading status), updating the DOM when state changes, handling two-way data binding between UI and internal state, and avoiding state inconsistencies.
Practice Interview
Study Questions
DOM Manipulation and Event Handling
Creating and modifying DOM elements, attaching event listeners, handling user interactions (click, hover, keyboard), event delegation, and managing element lifecycle. Writing vanilla JavaScript without framework abstractions.
Practice Interview
Study Questions
Accessibility and User Experience
Ensuring components are keyboard navigable, screen reader compatible, have sufficient color contrast, support ARIA labels and roles, and work well for users with disabilities. Understanding inclusive design principles.
Practice Interview
Study Questions
HTML Semantic Markup and Forms
Writing semantic HTML (using proper elements like <button>, <input>, <form>, <label>, <nav>), form submission and validation, handling form data, and understanding accessibility attributes (aria-label, role, aria-expanded).
Practice Interview
Study Questions
Onsite Round 2: Frontend System Design
What to Expect
A discussion round where you design the architecture of a large-scale frontend feature or application. For entry-level candidates, expect questions like: 'Design the search and filtering UI for Airbnb listings,' 'Architect a real-time chat interface,' or 'Design a photo gallery with recommendations.' You'll discuss component structure, state management approach, API contracts, performance optimization, and scalability. The focus for entry-level is demonstrating understanding of frontend fundamentals and basic architectural thinking—not complex distributed systems, but rather sensible component hierarchies, data flow patterns, and performance considerations.
Tips & Advice
Start by clarifying requirements and constraints: What's the scale? Who are the users? What are the primary interactions? Sketch a basic component hierarchy on the board/screen. Discuss data flow: where does data come from? How is it stored? How is it updated? Talk about key decisions: should we use SSR or CSR? How do we handle caching? What about error handling and loading states? For entry-level, focus on clarity and fundamental sound design rather than premature optimization. Discuss trade-offs openly: explain why you chose one approach over another. Ask questions when unsure rather than guessing. Interviewers want to see you think through problems systematically, not that you know every answer.
Focus Topics
Server-Side Rendering (SSR) vs. Client-Side Rendering (CSR) Trade-offs
Understanding when to use SSR (better SEO, faster initial load) vs. CSR (smoother interactions, reduced server load), discussing hybrid approaches, and considering the trade-offs based on requirements.
Practice Interview
Study Questions
Performance Considerations at Scale
Discussing lazy loading, code splitting, image optimization, caching strategies, infinite scroll vs. pagination, and how design decisions impact performance. Understanding perceived performance improvements like skeleton screens.
Practice Interview
Study Questions
Accessibility and User Experience in Architecture
Ensuring the overall system design supports accessible features, keyboard navigation, screen reader compatibility, progressive enhancement, and inclusive design principles from the architecture level.
Practice Interview
Study Questions
API Design and Data Integration
Designing or discussing API contracts that frontend needs, understanding pagination and filtering, handling async data fetching, managing loading and error states, and caching strategies.
Practice Interview
Study Questions
State Management Patterns
Choosing appropriate state management strategies (local component state, lifting state up, context, or simple state management libraries), understanding when to centralize vs. distribute state, and managing complex state flows.
Practice Interview
Study Questions
Component Architecture and Hierarchy
Designing component structures for large features, breaking down UIs into reusable, composable components, understanding component responsibilities, and planning props/state flow through the hierarchy.
Practice Interview
Study Questions
Onsite Round 3: Code Review
What to Expect
You'll review actual code (or a realistic code sample) and provide constructive feedback. Scenarios might include: reviewing a pull request for a rating widget, evaluating a dropdown component, or assessing test coverage strategies. You'll discuss code quality, identifying bugs or edge cases, checking for accessibility compliance, evaluating test coverage, suggesting improvements, and balancing perfection with pragmatism. For entry-level candidates, this evaluates your ability to read and understand code, think critically about quality, and communicate feedback respectfully. You're not expected to be an expert reviewer but should apply frontend fundamentals and best practices.
Tips & Advice
When reviewing code, check for: correctness (does it work?), readability (is it understandable?), accessibility (does it work for all users?), performance (are there obvious inefficiencies?), and testability (can it be tested?). Look for common issues: missing event listeners, unhandled edge cases, poor variable names, hardcoded values, missing ARIA labels. Provide specific, actionable feedback rather than vague criticism. Suggest improvements with reasoning: 'This component could be more accessible by adding aria-label here because...' Ask questions rather than making assumptions. For entry-level, it's okay to say 'I'm not sure about this pattern; can you explain the reasoning?' Interviewers respect humility. Prioritize critical issues (bugs, accessibility, security) over stylistic preferences.
Focus Topics
Performance Review and Optimization Opportunities
Spotting potential performance issues (unnecessary re-renders, inefficient loops, missing memoization), understanding performance implications of design choices, and suggesting optimization approaches.
Practice Interview
Study Questions
Test Coverage and Testing Strategy
Evaluating whether test coverage is adequate, balancing test depth with development speed, identifying critical paths that need testing, understanding unit vs. integration vs. end-to-end tests, and suggesting testing improvements.
Practice Interview
Study Questions
Code Quality and Best Practices
Evaluating code clarity, maintainability, naming conventions, avoiding code duplication, proper use of language features, and adherence to frontend best practices. Identifying anti-patterns and suggesting improvements.
Practice Interview
Study Questions
Accessibility Compliance in Code Review
Checking for semantic HTML usage, ARIA labels and roles, keyboard navigation support, color contrast, screen reader compatibility, and evaluating whether the code follows accessibility standards like WCAG.
Practice Interview
Study Questions
Bug Detection and Edge Case Analysis
Identifying bugs by tracing through code logic, spotting unhandled edge cases (null values, empty states, errors), recognizing potential runtime errors, and understanding state consistency issues.
Practice Interview
Study Questions
Onsite Round 4: Behavioral and Situational
What to Expect
A conversation-based round evaluating cultural fit, teamwork, learning ability, and how you handle real-world situations. You'll be asked about past experiences, how you approach problems, conflicts with teammates, learning from failures, and alignment with Airbnb values like 'belong anywhere.' For entry-level candidates, the focus is on demonstrating coachability, curiosity, collaboration, and how your past experiences (academic, internship, personal projects) show these qualities. You're not expected to have solved massive production issues; rather, interviewers look for potential, attitude, and alignment.
Tips & Advice
Prepare stories using the STAR method (Situation, Task, Action, Result) from your projects, internships, or academic experiences. Focus on moments where you learned something, collaborated well, faced a challenge, or solved a problem creatively. Be honest—interviewers can sense inauthenticity. For entry-level, it's okay to say 'I haven't faced that exact scenario, but here's something similar...' Listen carefully to questions and answer them directly. Show genuine interest in Airbnb by asking thoughtful questions about the team, culture, or how they approach problems. Discuss how Airbnb's values (especially 'belong anywhere') resonate with your philosophy. Give specific examples rather than generic answers. If asked about a weakness, mention something real but not disqualifying, and explain how you're working to improve.
Focus Topics
Problem-Solving Approach and Curiosity
Describing how you approach unfamiliar problems, resources you use (documentation, Stack Overflow, asking colleagues), and examples of projects where you had to learn new concepts or technologies.
Practice Interview
Study Questions
User-Centric Thinking
Discussing experiences where you considered user experience, accessibility, or user feedback in your work. Showing how you think about impact beyond code to the actual user.
Practice Interview
Study Questions
Teamwork and Collaboration
Sharing experiences of working with others (classmates, teammates, mentors), how you communicate about technical decisions, resolving disagreements, giving and receiving feedback, and supporting team members.
Practice Interview
Study Questions
Learning from Failure and Growth Mindset
Discussing a project that didn't go as planned, a bug you introduced, or a technology you struggled to learn. Explaining how you handled it, what you learned, and how you've applied that learning.
Practice Interview
Study Questions
Airbnb Core Value: Belong Anywhere
Understanding and articulating how inclusive design, diversity, and creating belonging inform your approach to building products. Discussing past experiences where you considered diverse user needs or promoted inclusivity.
Practice Interview
Study Questions
Frequently Asked Frontend Developer Interview Questions
Given historical stock prices in an array prices where prices[i] is the price at day i, implement in Python an algorithm to compute the maximum profit with at most k transactions. Discuss time/space trade-offs for k small vs k large and how to optimize for large N and small k.
Sample Answer
Direct answer
Track two running arrays indexed by "how many transactions used so far": buy[j] (best running profit while holding a share, having started the j-th buy) and sell[j] (best running profit while not holding, having completed the j-th sell), and update both for every price in a single left-to-right pass. This is O(n * k) time and O(k) space. There is also a special case: once k is at least n // 2, there can never be more than n // 2 genuinely profitable non-overlapping transactions regardless of how large k is, so the problem collapses to unlimited transactions, solvable greedily in O(n) time by summing every positive day-to-day price increase.
Algorithm
For each day's price, and for each transaction count j from 1 to k:
buy[j] = max(buy[j], sell[j-1] - price): either keep the best "holding" position already found for the j-th buy, or start a new j-th buy today, financed by whatever profit was banked after the (j-1)-th sell.sell[j] = max(sell[j], buy[j] + price): either keep the best "sold" position already found for the j-th sell, or sell today's holding for today's price.
Because buy[j] on the right-hand side is this day's just-updated value, sell[j] on the same day can reflect a buy-and-sell on the same day (a net-zero move, which never hurts an optimal solution since it's equivalent to not trading), while still processing the array in one pass with two length-(k+1) arrays rather than a full 2D table.
def max_profit_k_transactions(prices, k):
n = len(prices)
if n == 0 or k == 0:
return 0
if k >= n // 2:
return sum(max(0, prices[i] - prices[i - 1]) for i in range(1, n))
buy = [float("-inf")] * (k + 1)
sell = [0] * (k + 1)
for price in prices:
for j in range(1, k + 1):
buy[j] = max(buy[j], sell[j - 1] - price)
sell[j] = max(sell[j], buy[j] + price)
return sell[k]
Why k >= n // 2 collapses to unlimited transactions
Every transaction consumes at least 2 distinct days (one buy day, one sell day), and a set of non-overlapping transactions can't reuse a day. So no more than n // 2 transactions can ever be simultaneously "active" in an optimal non-overlapping schedule; once the allowed k reaches that ceiling, the constraint is no longer binding; you may as well capture every single profitable up-move independently, since doing so never uses more than n // 2 actual buy/sell pairs (adjacent up-runs merge into one transaction each) and no constrained schedule can beat the unconstrained greedy optimum.
Worked example
from functools import lru_cache
def max_profit_memoized(prices, k):
n = len(prices)
@lru_cache(maxsize=None)
def rec(day, txns_used, holding):
if day == n or txns_used == k:
return 0
best = rec(day + 1, txns_used, holding)
if holding:
best = max(best, prices[day] + rec(day + 1, txns_used + 1, False))
else:
best = max(best, -prices[day] + rec(day + 1, txns_used, True))
return best
result = rec(0, 0, False)
rec.cache_clear()
return result
cases = [
([2, 4, 1], 2),
([3, 2, 6, 5, 0, 3], 2),
([1, 2, 4, 2, 5, 7, 2, 4, 9, 0], 3),
]
for prices, k in cases:
fast = max_profit_k_transactions(prices, k)
memoized = max_profit_memoized(prices, k)
print(f"max_profit_k_transactions({prices}, k={k}) = {fast} (memoized cross-check: {memoized}, agree: {fast == memoized})")
Output (verified by execution, and cross-checked against an independently-implemented memoized recursion over (day, transactions_used, holding) for every case, a genuinely different formulation, not the same array-DP checked against itself):
max_profit_k_transactions([2, 4, 1], k=2) = 2 (memoized cross-check: 2, agree: True)
max_profit_k_transactions([3, 2, 6, 5, 0, 3], k=2) = 7 (memoized cross-check: 7, agree: True)
max_profit_k_transactions([1, 2, 4, 2, 5, 7, 2, 4, 9, 0], k=3) = 15 (memoized cross-check: 15, agree: True)
For [3, 2, 6, 5, 0, 3] with k=2: the optimal schedule is buy at 2 (index 1), sell at 6 (index 2), profit 4; buy at 0 (index 4), sell at 3 (index 5), profit 3; total 7, using exactly 2 of the allowed 2 transactions, matching the DP's answer. For [1, 2, 4, 2, 5, 7, 2, 4, 9, 0] with k=3: buy 1 sell 4 (profit 3), buy 2 sell 7 (profit 5), buy 2 sell 9 (profit 7), total 15, again using all 3 allowed transactions and matching the largest 3 disjoint up-runs in the sequence.
Trade-offs and pitfalls
- k small vs k large is a genuine complexity cliff, not a smooth trade-off: for small
k(say, single or low double digits), O(n*k) is fast and the array-DP above is the right tool. For largek(specifically oncek >= n // 2), the same DP still gives the correct answer but does unnecessary work; recognizing and special-casing the collapse to the O(n) greedy is the difference between an interviewer seeing a complete answer and a merely correct-but-naive one. - Off-by-one in the collapse threshold is a common mistake: it's
n // 2, notn / 2rounded up orn - 1; a schedule needs 2 distinct days per transaction, sondays support at mostn // 2non-overlapping transactions (floor division). - The
buy[j] = sell[j-1] - pricerecurrence is the crux most people get wrong on their own the first time: it's tempting to writebuy[j] - price(buying doesn't "cost" anything against your own already-open position; it should reset from the state before this transaction started, i.e.,sell[j-1], the profit banked from the previous, already-closed transaction). - This is a good example of the topic's own boundary: the natural solution technique here is DP-style state tracking over transaction count, but the practical implementation is two flat arrays updated in a single array pass, not a full 2D recursive table, the same reasoning that keeps Kadane's algorithm and expand-around-center palindrome checks classified as array-manipulation technique rather than routed to a dedicated dynamic-programming topic.
A scroll handler loops over elements, reading offsetHeight or getBoundingClientRect and then writing a style on each, and the page stutters. Explain what is happening and refactor it.
Sample Answer
Direct answer
The handler causes forced synchronous layout, repeated once per element, which is called layout thrashing. Layout is the browser's step of working out each element's size and position. It follows style recalculation, the earlier step of working out which CSS rules apply to each element and what its final values are; both steps are postponed in the same way, and a layout read needs both to be up to date. Normally the browser postpones it until the next frame (one screen refresh, typically 60 per second on a 60 Hz display), but reading offsetHeight or getBoundingClientRect() asks for an up-to-date answer, so if an earlier line in the same task changed a layout-affecting style, the browser must stop and run layout right then. Alternating read, write, read, write inside a loop therefore runs layout up to once per iteration. The fix is to do all the reads first, then all the writes, so layout runs once, and to run that work at most once per frame.
Diagnosis, in order
- Record a Performance trace while scrolling (DevTools, Performance panel). A task is one uninterrupted chunk of main-thread work, drawn as a bar in the Main track; the bars nested under it show which functions ran and which browser steps they triggered. A thrashing handler shows up as one long task with many separate Layout bars nested under your function, instead of a single Layout bar after it. DevTools also reports a Forced Reflow insight that points at the offending line (web.dev describes this insight as the way to find forced synchronous layouts).
- Confirm in the code. Look inside the loop for a read of a layout value (
offsetHeight,offsetWidth,clientHeight,scrollTop,getBoundingClientRect(),getClientRects(),innerText, and somegetComputedStylereads) that comes after a write towidth,height,top,left,padding,margin, a class that changes any of them, orinnerHTML. web.dev lists the geometric propertieswidth,height,leftandtopas ones whose changes require layout. - Count it. The harness below reads Chromium's
LayoutCountcounter through the DevTools protocol before and after one scroll. The count is a number you can compare after the fix, unlike an impression of smoothness. - Refactor, then repeat steps 1 and 3 and confirm the count dropped and the visible result is unchanged.
The refactor
// Before: each iteration's read has to wait for the previous iteration's write to be laid out.
for (const el of rows) {
const top = el.getBoundingClientRect().top; // read
el.style.paddingLeft = (top < 0 ? 24 : 0) + 'px'; // write
}
// After: reads together, then writes together, and a class instead of inline style.
const above = rows.map((el) => el.getBoundingClientRect().top < 0); // read pass
rows.forEach((el, i) => el.classList.toggle('shifted', above[i])); // write pass
Further steps, each independent of the others:
- Cache measurements that do not change on scroll. A row's own height does not change while scrolling, so measure it once and refresh it when a
ResizeObserver(an API that reports size changes of an element) fires, instead of re-measuring on every event. - Separate read and write passes as above. The first read in a batch may pay for pending layout, but only that one does.
- Prefer class toggles to inline
stylewrites. The values live in CSS and the JS only chooses a state, which also keeps magic numbers out of the script. - Run at most once per frame. Whatever the handler does only becomes visible at the next frame, so set a flag and do the work inside
requestAnimationFrame(a function that asks the browser to call your callback just before the next frame): five events before one frame then cost one run (the last line of the printed output). - Do not measure at all when the question is "is it visible". An
IntersectionObserver(an API that calls your function when an element enters or leaves the viewport) delivers visibility changes without any layout read in your code.
Measured result
The harness injects each handler into the page as source text: make.toString() turns the handler factory into a string, eval rebuilds it inside the page and calls it to get the handler, and { once: true } makes the scroll listener run a single time, then waitForFunction waits until it has run. The rest is bookkeeping: Performance.getMetrics through the DevTools protocol (the debugging channel Playwright uses to talk to Chromium) reports LayoutCount, the number of layouts run so far, read before and after the scroll, and a final getComputedStyle pass counts the indented rows. The three variants differ only in the handler they inject.
The harness scrolls a page of 300 rows (each 40 px high) down by 6000 px in Chromium, so rows 0 to 149 are above the top of the viewport and get indented, and it counts layouts for three handlers that produce the same visible result.
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const ROWS = 300;
const page_html = `<style>
body { margin: 0 }
.row { height: 40px; white-space: nowrap; overflow: hidden; box-sizing: border-box }
.shifted { padding-left: 24px }
</style>
<div id="app">${'<div class="row">row</div>'.repeat(ROWS)}</div>`;
// Each variant: a scroll handler that indents rows scrolled above the viewport top.
const variants = {
'thrashing (read, write, read, write)': () => {
const rows = [...document.querySelectorAll('.row')];
return () => {
for (const el of rows) {
const top = el.getBoundingClientRect().top; // read
el.style.paddingLeft = (top < 0 ? 24 : 0) + 'px'; // write: layout-affecting
}
};
},
'batched (all reads, then all writes)': () => {
const rows = [...document.querySelectorAll('.row')];
return () => {
const tops = rows.map((el) => el.getBoundingClientRect().top); // read pass
rows.forEach((el, i) => { el.style.paddingLeft = (tops[i] < 0 ? 24 : 0) + 'px'; }); // write pass
};
},
'batched + class toggle': () => {
const rows = [...document.querySelectorAll('.row')];
return () => {
const above = rows.map((el) => el.getBoundingClientRect().top < 0); // read pass
rows.forEach((el, i) => el.classList.toggle('shifted', above[i])); // write pass
};
},
};
const browser = await chromium.launch();
const results = {};
for (const [name, make] of Object.entries(variants)) {
const page = await browser.newPage();
const cdp = await page.context().newCDPSession(page);
await cdp.send('Performance.enable');
const layouts = async () => (await cdp.send('Performance.getMetrics')).metrics.find((m) => m.name === 'LayoutCount').value;
await page.setContent(page_html);
await page.evaluate((src) => {
const handler = eval(`(${src})`)();
window.__done = false;
window.addEventListener('scroll', () => { handler(); window.__done = true; }, { once: true });
}, make.toString());
await page.evaluate(() => document.body.offsetHeight); // settle initial layout
const before = await layouts();
await page.evaluate(() => window.scrollTo(0, 6000));
await page.waitForFunction(() => window.__done === true); // wait for the real scroll event
await page.evaluate(() => document.body.offsetHeight); // settle
const after = await layouts();
const shiftedRows = await page.evaluate(() => [...document.querySelectorAll('.row')].filter((el) => {
return getComputedStyle(el).paddingLeft === '24px'; }).length);
results[name] = { layouts: after - before, shiftedRows };
console.log(`${name.padEnd(40)} layouts=${results[name].layouts} rowsIndented=${shiftedRows}`);
await page.close();
}
await browser.close();
const t = results['thrashing (read, write, read, write)'];
const b = results['batched (all reads, then all writes)'];
const c = results['batched + class toggle'];
assert.ok(t.layouts >= ROWS / 2, 'thrashing variant should force about one layout per row');
assert.ok(b.layouts <= 3 && c.layouts <= 3, 'batched variants should need only a few layouts');
assert.equal(t.shiftedRows, b.shiftedRows); // same visible result
assert.equal(b.shiftedRows, c.shiftedRows);
assert.equal(t.shiftedRows, ROWS / 2);
console.log('same 150 rows indented by all three variants; thrashing costs far more layouts');
// Coalescing: however many scroll-like events arrive before the next frame, the layout work runs once.
{
const page = await (await chromium.launch()).newPage();
await page.setContent(page_html);
const runs = await page.evaluate(async () => {
let runs = 0, queued = false;
const work = () => { runs++; }; // the batched read/write pass goes here
const onScroll = () => {
if (queued) return;
queued = true;
requestAnimationFrame(() => { queued = false; work(); });
};
for (let i = 0; i < 5; i++) onScroll(); // five events in the same task
await new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r)));
return runs;
});
console.log(`5 events before the next frame -> work ran ${runs} time(s)`);
assert.equal(runs, 1);
await page.context().browser().close();
}
Run in the Playwright 1.48.2 image (Chromium only, since LayoutCount comes from the DevTools protocol), it prints:
thrashing (read, write, read, write) layouts=150 rowsIndented=150
batched (all reads, then all writes) layouts=1 rowsIndented=150
batched + class toggle layouts=1 rowsIndented=150
same 150 rows indented by all three variants; thrashing costs far more layouts
5 events before the next frame -> work ran 1 time(s)
Why 150 and not 300 for the thrashing version: a write only dirties layout when it changes the computed value. Rows 150 to 299 are written with 0px, which they already had, so those iterations found layout still clean. The count therefore tracks the number of rows whose value changes, up to the number of rows; it grows with the row count while the batched versions stay at one. The harness asserts that the thrashing variant needs at least half as many layouts as there are rows, that the batched variants need three or fewer, and that all three indent exactly the same 150 rows, so it fails if the refactor changes behaviour. Repeated runs print identical output because every figure is a count, not a time.
Pitfalls and edge cases
- Batching changes semantics when reads depend on earlier writes. In the thrashing loop, row 5's measurement already includes the effect of rows 0 to 4's writes; in the batched loop it does not. That is the intended behaviour when the reads are independent, but if each row's position depends on the previous row's new size, you need a different algorithm (compute positions arithmetically from the measured sizes), not just reordering.
- Hidden reads. Libraries and getters (
el.offsetParent,focus(),scrollIntoView(), layout-dependentgetComputedStylevalues) also force layout, so a loop that "does not read anything" may still thrash. - A single forced layout is fine. One read at the start of a handler costs one layout, which the browser would have done anyway at the next frame.
- Complexity. Thrashing costs O(rows) layouts, each proportional to the affected part of the page; batching costs O(rows) reads and writes but one layout.
Running the code
# package.json must contain {"type":"module"}; save the listing as scroll-thrash.mjs
docker run --rm -v "$PWD":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \
sh -c "npm i playwright@1.48.2 && node scroll-thrash.mjs"
A company you are interviewing with publishes an explicit mission statement and a short list of core values or operating principles. Pick one such value, explain what you understand it to mean in practice, and describe how it would shape your day-to-day decisions in this role.
Sample Answer
Direct answer
I'll use Amazon's "Customer Obsession" as the example: in plain terms it means starting from the customer's actual experience and working backward to the decision, rather than starting from what's easiest or cheapest for the team and working forward to how it will land on the customer. In day-to-day work that shows up as a specific, repeatable habit: before finalizing a decision, explicitly write down what the customer will experience as a result, not just what the team will ship.
Structured elaboration
- State the value in plain language first, in one or two sentences, before layering on any nuance. A stated value is only useful if you can restate it without jargon; if you can't, you probably don't understand it well enough to apply it.
- Trace two or three concrete decisions the value would actually change, not just decisions it would be compatible with. The test is not "does this decision fit the value" (almost any reasonable decision can be described as fitting almost any value after the fact); the test is "would I have decided differently without this value in mind."
- Be specific about the mechanism, not just the outcome. It's not enough to say "I'd focus on the customer"; describe the actual practice (writing the customer-facing consequence down explicitly, reviewing a metric that measures customer impact rather than only internal effort, asking a specific question in a design review) that operationalizes the value day to day.
- Acknowledge the value has a cost or a trade-off, because a value with no real cost usually is not being taken seriously. A genuinely operative value changes what you'd otherwise have done, which means it sometimes means doing the harder or slower thing.
- Connect it back to your own role specifically, since the same value plays out differently for different functions; the mechanism for a backend engineer, a designer, and an analyst are all different concrete practices in service of the same underlying value.
Worked example
Say you're building a dashboard intended to help a seller reduce order defects. A team NOT applying customer obsession as a working discipline might ship the dashboard once the underlying data pipeline is stable and the metrics are technically correct, treating "the data is right" as the finish line. Applying the value changes the finish line: before shipping, you'd sit with two or three actual sellers using an early version and ask what decision they're trying to make when they open it, which might surface that they need same-day defect data to catch a bad batch before it ships further, not a metric that's accurate but a day stale. The concrete decision that changes: you invest in a same-day data refresh even though it's more engineering effort than the weekly batch job you'd planned, because the customer's real decision-making need, not the easier technical path, is what determines what "done" means. The cost is real (more pipeline complexity, tighter SLAs to maintain) which is exactly why it's evidence the value is actually operative rather than decorative.
Trade-offs & pitfalls
The most common failure is reciting the value's definition fluently and then giving an example so generic it would apply to any company with any stated value ("I always think about the user"), which demonstrates you've read the careers page rather than that you understand the mechanism. A second pitfall is picking an example where the value cost nothing: if every example you give was also simply the obviously correct engineering or business call regardless of the stated value, you haven't actually shown the value did any independent work in your reasoning. A third is over-indexing on one company's specific phrasing so heavily that the answer would sound out of place at any other employer; the goal is to show you can genuinely reason from a stated principle to a concrete decision, a transferable skill, not that you've memorized one company's vocabulary.
A component keeps both a list of items and a filteredItems list in state, and the two sometimes disagree. Why does that happen, and how do you decide what to store versus compute during render? When is caching a computed value justified?
Sample Answer
The two lists disagree because the same fact is stored twice, and every code path that changes one must remember to change the other; one path forgets. Store the minimum (items and the query), and compute filteredItems during render, which makes it a derived value: one you can always calculate from other state or props, such as match(items, query). Cache the computed value with useMemo (a hook that remembers the result of a calculation between renders and re-runs it only when a value in its dependency list changes) only after you have measured that the calculation is slow and see it re-running for unrelated renders.
Why they disagree
The component below keeps items and filtered. The query handler updates both. The add handler updates only items. With the filter an active, adding mango leaves filtered as ['banana'] while items holds four entries. The test shows exactly this.
"If you can calculate some information from the component's props or its existing state variables during rendering, you should not put that information into that component's state." (react.dev, Choosing the State Structure)
The same page lists "Avoid duplication in state" as a principle: duplicated data "is difficult to keep them in sync."
Deciding what to store
Ask in order:
- Can it be calculated from other state or props? Compute it (the filtered list, a count, a selected object looked up by id).
- If it cannot be calculated from anything else, it is real state. The text typed into the search box is state, because nothing else records what the user typed; the on/off flag behind a theme button is state for the same reason. The filtered list is not: given
itemsand the query, it is always the same. - Is it used only by this component? Keep it local. Do siblings need it? Lift it to the nearest common parent. Many distant readers? A context or store.
- Store ids, not copies:
selectedIdanditems.find(...), not a secondselectedItemobject.
Derived values also test more easily: match(items, q) is a pure function you can assert on without rendering.
When caching a computed value is justified
When the calculation is slow enough to show up when you measure it (the React docs suggest console.time around it and treat about 1 ms or more per interaction as a candidate), and unrelated renders trigger it. The run counts calls to the filter function: with plain computation it ran on mount and on each of 4 theme clicks (5 calls); with useMemo it ran once on mount, and again only when the query changed. The cache must be correct without being trusted: React's docs state that useMemo is a performance optimization and not a semantic guarantee, so the result must be the same whether or not the cache holds.
// redundant-state.test.jsx
import { useState, useMemo } from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
const seed = ['apple', 'banana', 'cherry'];
const match = (items, q) => items.filter(x => x.includes(q));
// Two stores of the same fact: the add handler updates only one of them.
function Duplicated() {
const [items, setItems] = useState(seed);
const [filtered, setFiltered] = useState(seed);
const [q, setQ] = useState('');
return <>
<input aria-label="q" value={q} onChange={e => { setQ(e.target.value); setFiltered(match(items, e.target.value)); }} />
<button onClick={() => setItems([...items, 'mango'])}>add</button>
<output aria-label="count">{items.length}</output>
<ul>{filtered.map(x => <li key={x}>{x}</li>)}</ul></>;
}
// One source of truth (items, q); the visible list is computed in render.
let filterCalls = 0;
const visiblePlain = (items, q) => { filterCalls++; return match(items, q); };
const visibleCached = (items, q) => useMemo(() => { filterCalls++; return match(items, q); }, [items, q]);
function Derived({ useVisible = visiblePlain }) {
const [items, setItems] = useState(seed);
const [q, setQ] = useState('');
const [dark, setDark] = useState(false);
const visible = useVisible(items, q);
return <div data-dark={dark}>
<input aria-label="q" value={q} onChange={e => setQ(e.target.value)} />
<button onClick={() => setItems([...items, 'mango'])}>add</button>
<button onClick={() => setDark(!dark)}>theme</button>
<ul>{visible.map(x => <li key={x}>{x}</li>)}</ul></div>;
}
const texts = () => screen.queryAllByRole('listitem').map(li => li.textContent);
function scenario(C) {
render(<C />);
fireEvent.change(screen.getByLabelText('q'), { target: { value: 'an' } });
fireEvent.click(screen.getByText('add')); // 'mango' contains 'an'
expect(texts()).toEqual(['banana', 'mango']);
}
test('derived list stays consistent when items change under an active filter', () => scenario(Derived));
test('control: duplicated filteredItems disagrees with items', () => {
render(<Duplicated />);
fireEvent.change(screen.getByLabelText('q'), { target: { value: 'an' } });
fireEvent.click(screen.getByText('add'));
console.log('duplicated list shows:', texts(), 'items held:', screen.getByLabelText('count').textContent);
expect(texts()).toEqual(['banana']); // stale: 'mango' is missing
expect(screen.getByLabelText('count').textContent).toBe('4'); // yet items did change
});
test('caching the derived value skips work only when inputs are unchanged', () => {
for (const memo of [false, true]) {
document.body.innerHTML = ''; filterCalls = 0;
const { unmount } = render(<Derived useVisible={memo ? visibleCached : visiblePlain} />);
for (let i = 0; i < 4; i++) fireEvent.click(screen.getByText('theme'));
const unrelated = filterCalls;
fireEvent.change(screen.getByLabelText('q'), { target: { value: 'an' } });
console.log(`memo=${memo}: filter calls after mount + 4 theme clicks = ${unrelated}, after one query edit = ${filterCalls}`);
expect(unrelated).toBe(memo ? 1 : 5);
expect(filterCalls).toBe(memo ? 2 : 6);
expect(texts()).toEqual(['banana']);
unmount();
}
});
Printed by the run:
duplicated list shows: [ 'banana' ] items held: 4
memo=false: filter calls after mount + 4 theme clicks = 5, after one query edit = 6
memo=true: filter calls after mount + 4 theme clicks = 1, after one query edit = 2
The filter calls, render by render:
| Render | Cause | memo=false calls so far | memo=true calls so far |
|---|---|---|---|
| 1 | mount | 1 | 1 |
| 2 to 5 | four theme clicks (items and q unchanged) | 5 | 1 (dependencies unchanged, cached result reused) |
| 6 | one query edit (q changed from empty to an) | 6 | 2 (dependency changed, recomputed) |
Plain computation runs the filter on every render (1 + 4 + 1 = 6); useMemo runs it on the mount and on the one render where a dependency changed (1 + 1 = 2).
Pitfalls
- Fixing the symptom with an effect (code React runs after rendering, written with
useEffect, normally used to sync with something outside React) that copiesitemsintofilteredkeeps two sources of truth that can still disagree. - Memoizing a derived value that has an array or object in its dependency list only helps if those inputs keep their identity between renders.
- Server-fed or user-typed data that you are not allowed to transform may be a case for real state; derived means a pure function of other state.
Running the code
Tested with Node 22, React 18.3.1, jsdom 25.0.1 and Vitest 2.1.4.
mkdir demo && cd demo && npm init -y
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.mjs
echo "export default { esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom', globals: true } };" > vitest.config.mjs
# save redundant-state.test.jsx next to it, then (Node 22):
npx vitest run redundant-state.test.jsx
How should heading elements be used on a page, and why does a logical heading hierarchy matter for screen-reader users? A page has an h1 followed by h4s chosen for their size. What is wrong and how do you fix it?
Sample Answer
Direct answer
Headings (<h1> to <h6>) are the page's outline: each one names a section, and its number says how deeply that section is nested inside the one above. Use one <h1> for the page's subject, <h2> for its main sections, <h3> for subsections of those, and never pick a level because of how large it looks. A page with an <h1> followed by <h4>s skips two levels, so the outline claims there are missing <h2> and <h3> sections; the fix is to mark those headings up as <h2> and control their size with a CSS class.
Terms: a screen reader is software that reads a page aloud or to a braille display; a heading level is the number in h1 to h6; the accessibility tree is the browser's version of the page that assistive technology reads; a class for size is a CSS class that sets how large the text looks, so size is decided separately from the element's meaning.
Why the hierarchy matters to screen-reader users
MDN describes the behaviour: "A common navigation technique for users of screen reading software is to quickly jump from heading to heading in order to determine the content of the page. Because of this, it is important to not skip one or more heading levels. Doing so may create confusion, as the person navigating this way may be left wondering where the missing heading is."
So headings work as a table of contents the user can skim. The level communicates structure: an h2 is a sibling of other h2s and a child of the h1. When the list reads h1, h4, h4 the user hears a hierarchy with two missing tiers and cannot tell whether content was lost, whether the h4s are children of something unseen, or whether the page is simply built wrongly. Font size is only a visual cue; it is not part of the outline that assistive technology reads, so a large h4 and a small h2 look right and still describe the wrong structure.
How to use headings
- One
<h1>describing the page. MDN: using several<h1>s "is allowed by the HTML standard", but "is not considered a best practice", and a page "should generally have a single<h1>element that describes the content of the page". - Nest without skipping going down. MDN: "Do not skip heading levels: always start from
<h1>, followed by<h2>and so on." Going back up by several levels (anh4followed by anh2for the next major section) is normal; it is the downward jumps that leave gaps. - Headings are for sections, not for styling. MDN: "Do not use heading elements to resize text. Instead, use the CSS
font-sizeproperty." - Do not fake headings. Bold
<p>text that looks like a heading is invisible in the outline, so real section titles need real heading elements.
The broken page and the fix
The broken page picks h4 because its default size (16px here) matched the design. The browser's default h4 also carries a larger vertical margin (1.33em) than an h2 (0.83em), so the class must set the margin too if the layout is to stay put. The fix keeps the look and changes the meaning:
<!-- before: h1 then h4, h4 -->
<h1>Pricing</h1>
<h4>Free plan</h4><p>For hobby projects.</p>
<h4>Pro plan</h4><p>For teams.</p>
<!-- after: h1 then h2, h2, sized by a class -->
<style>.plan-title { font-size: 1rem; margin-block: 1.33em; }</style>
<h1>Pricing</h1>
<h2 class="plan-title">Free plan</h2><p>For hobby projects.</p>
<h2 class="plan-title">Pro plan</h2><p>For teams.</p>
If the plans were themselves subsections of a "Plans" section, the right structure is h1 Pricing, h2 Plans, h3 for each plan. Which level is correct depends on the content's nesting, never on the size wanted; choose the level from the outline and then style it.
A short check function finds the problem mechanically: for each heading after the first, if its level is more than one deeper than the previous heading, report the jump. The script runs it on both versions, prints the computed font sizes, heading margins and paragraph positions to show the fix leaves the layout unchanged, and prints the heading levels from Chromium's accessibility tree (this is what assistive technology reads from the browser, not a screen reader).
import { chromium } from 'playwright';
const bad = `<!doctype html>
<h1>Pricing</h1>
<h4>Free plan</h4><p>For hobby projects.</p>
<h4>Pro plan</h4><p>For teams.</p>`;
const good = `<!doctype html>
<style>.plan-title { font-size: 1rem; margin-block: 1.33em; }</style>
<h1>Pricing</h1>
<h2 class="plan-title">Free plan</h2><p>For hobby projects.</p>
<h2 class="plan-title">Pro plan</h2><p>For teams.</p>`;
// Returns every place where the next heading is more than one level deeper than the previous one.
export const skippedLevels = (levels) =>
levels.flatMap((l, i) => (i > 0 && l > levels[i - 1] + 1 ? [`h${levels[i - 1]} -> h${l}`] : []));
const browser = await chromium.launch();
const page = await browser.newPage();
for (const [label, html] of [['h1 then h4', bad], ['h1 then h2.plan-title', good]]) {
await page.setContent(html);
const levels = await page.$$eval('h1,h2,h3,h4,h5,h6', (hs) => hs.map((h) => Number(h.tagName[1])));
const looks = await page.$$eval('h1,h2,h3,h4,h5,h6', (hs) =>
hs.map((h) => { const s = getComputedStyle(h); return `${s.fontSize}/${s.marginTop}`; }));
const tops = await page.$$eval('p', (ps) => ps.map((p) => Math.round(p.getBoundingClientRect().top)));
const tree = [];
(function walk(n) { if (n.role === 'heading') tree.push(`${n.name} (level ${n.level})`); (n.children || []).forEach(walk); })(await page.accessibility.snapshot());
console.log(label);
console.log(' DOM levels:', levels.join(','), '| skipped:', JSON.stringify(skippedLevels(levels)));
console.log(' font size/margin-top:', looks.join(', '));
console.log(' paragraph tops (px):', tops.join(', '));
console.log(' Chromium accessibility tree:', tree.join(' | '));
}
await browser.close();
Output:
h1 then h4
DOM levels: 1,4,4 | skipped: ["h1 -> h4"]
font size/margin-top: 32px/21.44px, 16px/21.28px, 16px/21.28px
paragraph tops (px): 119, 198
Chromium accessibility tree: Pricing (level 1) | Free plan (level 4) | Pro plan (level 4)
h1 then h2.plan-title
DOM levels: 1,2,2 | skipped: []
font size/margin-top: 32px/21.44px, 16px/21.28px, 16px/21.28px
paragraph tops (px): 119, 198
Chromium accessibility tree: Pricing (level 1) | Free plan (level 2) | Pro plan (level 2)
The sizes, margins and paragraph positions match (32px for the h1, 16px for each plan title, paragraphs at 119px and 198px in both pages), the first outline has one jump (h1 -> h4), and the second has none. Without the margin-block line the same fix moves the paragraphs to 114px and 182px, because h2 has a smaller default margin than h4; changing the element changes its default styles as well as its meaning.
Trade-offs and pitfalls
- Component libraries often couple level and size in one prop (
<Heading size="sm">that renders anh4). Separate them: alevelprop that sets the element and asizeor class prop that sets the look. - Reusable components cannot know their depth. Let the parent pass the level, or compute it from context, rather than hard-coding an
h3that is wrong on half the pages it appears on. - Heading text should make sense out of context, since the heading list is read without the paragraphs between: "Pro plan" beats "Learn more".
- A heading should introduce content. An empty heading, or one wrapping only decoration, adds a stop to the list with nothing under it.
- Edge cases: a page with no headings has an empty outline; an
h2followed by anh3is correct nesting, not a skip; a page that jumps fromh1straight toh3fails the same check as theh1,h4page above.
Running the code
mkdir demo && cd demo # put check.mjs here
npm init -y && npm pkg set type=module
npm i playwright@1.48.2 && npx playwright install chromium
node check.mjs
Three internal microservices each use a different auth scheme, pagination style and error format, and your web app has to render screens from all of them. Design the Backend-for-Frontend that sits in front. What belongs in it, what should stay out of it, and when would you rather normalize in the frontend instead?
Sample Answer
Direct answer
The BFF (Backend-for-Frontend, a server owned by the web team whose only customer is the web app) should absorb the differences between the services: authentication to each upstream, pagination, error format, timeouts and partial failure, plus the joining and trimming that one screen needs. It should not hold business rules, a database of record, or presentation concerns such as button labels. Normalize in the frontend only when the data comes from a single service, needs no secret, and is already shaped the way the UI wants it.
The three services in this scenario are a concrete example of the BFF's job: service A uses a bearer token (a credential sent in the Authorization: Bearer <token> header), offset pagination and {error: "..."}; service B uses an API key header, cursor pagination and {errors: [{code, detail}]}; service C uses a session cookie (a service session the BFF holds), page numbers and plain-text errors.
The three pagination styles ask for "the next page" in three different ways. Using the same lists as the runnable skeleton below:
| Style | Request for the next page | How the server says there is more |
|---|---|---|
| Offset (skip this many items) | GET /orders?offset=3&limit=3 | total: 7, so the client works out that 6 is still below 7 |
| Cursor (a bookmark the server hands back) | GET /tickets?cursor=2 | next_cursor: 4, or null on the last page |
| Page number | GET /invoices?page=2 | pages: 2, so page 2 is the last |
The UI wants one pager component, so the BFF turns all three into {items, nextCursor}. An opaque cursor is a string the client sends back unchanged without interpreting it; here "3" is an offset for orders while "2" is a page number for invoices, and the UI never needs to know.
What the BFF does for a single browser request to an account screen: (1) check the browser's session with the BFF; (2) start three upstream calls at once, each with its own credential and a deadline; (3) rewrite each reply into the shared item and error shapes; (4) return one JSON object with one panel per service, so a failed service marks only its own panel.
What belongs in the BFF
| Concern | What the BFF does | Why here |
|---|---|---|
| Upstream authentication | Holds the credential each service wants (token, key, session) and attaches it; the browser only ever holds its own session with the BFF. | B's API key and C's service session cookie are credentials issued to the BFF, not to any user. They cannot be shipped to a browser at all, because anything in page JavaScript can be read by every visitor, so this is not a style choice. |
| Pagination | Presents one shape to the UI, {items, nextCursor}, with an opaque cursor string; the adapter translates it to offset, cursor or page number. | The UI needs one pager component, not three. |
| Error format | Maps every upstream failure to {code, message, retryable}. The message is the BFF's own wording; the upstream text stays on the server error object for logs and never reaches the panel. | Upstream messages can leak internals; the UI needs one error component. |
| Fan-out and failure | Calls upstreams in parallel, each with a deadline, and returns per-panel status instead of failing the whole screen. | One slow or broken service should degrade one panel. |
| Shaping | Renames and drops fields so the payload matches the screen. | Saves bytes and removes mapping code from the browser. |
| Read caching | Caches upstream GETs briefly, and coalesces identical in-flight requests (when a second identical request arrives while the first is still waiting, it shares the first one's result instead of calling the service again). | Protects the services from a screen that fires the same call twice. |
What stays out
- Business rules and authorization decisions (is this refund allowed, what does this plan cost). The services own them; the BFF forwards the caller's identity and lets the service decide. If the BFF copies a rule, the next client re-implements it differently.
- Its own database of record. A cache is fine; the only copy of anything is not.
- Cross-service transactions. If two writes must succeed together, that is a service-level workflow, not something the web BFF orchestrates.
- Presentation text and layout, such as formatted strings for a button. Keep the payload semantic and let the UI format; otherwise every copy change is a backend deploy.
- Blind retries of writes. Retry only idempotent reads (an idempotent request has the same effect whether it is sent once or five times, as a read does); a repeated POST can double-charge.
A runnable BFF skeleton
Three fake upstreams with the three styles, adapters that normalize them, and a screen function that returns partial results. Run in a node:22 container (Node 22.23.3) with node bff-aggregator.mjs; there is nothing to install.
// Three upstream services with different auth, pagination and error formats,
// and a BFF that normalizes them into one screen payload.
import http from 'node:http';
// ---------- upstream services (stand-ins for internal microservices) ----------
const orders = Array.from({ length: 7 }, (_, i) => ({ oid: 100 + i, total: 10 * (i + 1) }));
const tickets = Array.from({ length: 5 }, (_, i) => ({ id: 't' + i, subject: 'Issue ' + i }));
const invoices = Array.from({ length: 4 }, (_, i) => ({ no: 9000 + i, amount_due: 5 * i }));
function listen(handler) {
return new Promise((res) => {
const s = http.createServer(handler).listen(0, '127.0.0.1', () => res(s));
});
}
const json = (r, code, body) => { r.writeHead(code, { 'content-type': 'application/json' }); r.end(JSON.stringify(body)); };
// Service A: bearer token, offset pagination, errors as {error:"..."}
const A = await listen((q, r) => {
const u = new URL(q.url, 'http://x');
if (q.headers.authorization !== 'Bearer svc-a-token') return json(r, 401, { error: 'bad token' });
const off = +(u.searchParams.get('offset') ?? 0), lim = +(u.searchParams.get('limit') ?? 3);
json(r, 200, { items: orders.slice(off, off + lim), total: orders.length });
});
// Service B: API key header, cursor pagination, errors as {errors:[{code,detail}]}
const B = await listen((q, r) => {
const u = new URL(q.url, 'http://x');
if (q.headers['x-api-key'] !== 'svc-b-key') return json(r, 403, { errors: [{ code: 'FORBIDDEN', detail: 'bad key' }] });
const c = +(u.searchParams.get('cursor') ?? 0);
const data = tickets.slice(c, c + 2);
json(r, 200, { data, next_cursor: c + 2 < tickets.length ? c + 2 : null });
});
// Service C: session cookie, page-number pagination, errors as plain text. Mode: 'ok', 'down' (503) or 'hang' (never answers).
let cMode = 'ok';
const C = await listen((q, r) => {
if (cMode === 'hang') return;
if (cMode === 'down') { r.writeHead(503, { 'content-type': 'text/plain' }); return r.end('pool exhausted on db-7 (10.0.3.9)'); }
const u = new URL(q.url, 'http://x');
if (q.headers.cookie !== 'sid=svc-c-session') { r.writeHead(401, { 'content-type': 'text/plain' }); return r.end('login required'); }
const p = +(u.searchParams.get('page') ?? 1), size = 2;
json(r, 200, { results: invoices.slice((p - 1) * size, p * size), page: p, pages: Math.ceil(invoices.length / size) });
});
const url = (s) => `http://127.0.0.1:${s.address().port}`;
// ---------- the BFF: adapters hide auth, pagination and error differences ----------
// One normalized error shape and one normalized page shape: {items, nextCursor}
class UpstreamError extends Error {
constructor(source, status, code, message) { super(message); Object.assign(this, { source, status, code }); }
get retryable() { return this.status >= 500 || this.status === 429; }
}
async function call(source, u, headers) {
const ctl = AbortSignal.timeout(500); // every upstream call has a deadline
const res = await fetch(u, { headers, signal: ctl });
const text = await res.text();
if (!res.ok) {
let code = 'UPSTREAM_' + res.status, message = text;
try { const j = JSON.parse(text); message = j.error ?? j.errors?.[0]?.detail ?? text; code = j.errors?.[0]?.code ?? code; } catch {}
throw new UpstreamError(source, res.status, code, message);
}
return JSON.parse(text);
}
const adapters = {
orders: async (cursor) => { // cursor is the offset, encoded as a string
const off = cursor ? +cursor : 0;
const j = await call('orders', `${url(A)}/orders?offset=${off}&limit=3`, { authorization: 'Bearer svc-a-token' });
const next = off + j.items.length;
return { items: j.items.map((o) => ({ id: String(o.oid), amount: o.total })), nextCursor: next < j.total ? String(next) : null };
},
tickets: async (cursor) => {
const j = await call('tickets', `${url(B)}/tickets?cursor=${cursor ?? 0}`, { 'x-api-key': 'svc-b-key' });
return { items: j.data.map((t) => ({ id: t.id, title: t.subject })), nextCursor: j.next_cursor === null ? null : String(j.next_cursor) };
},
invoices: async (cursor) => {
const p = cursor ? +cursor : 1;
const j = await call('invoices', `${url(C)}/invoices?page=${p}`, { cookie: 'sid=svc-c-session' });
return { items: j.results.map((i) => ({ id: String(i.no), due: i.amount_due })), nextCursor: p < j.pages ? String(p + 1) : null };
},
};
// The screen endpoint: one browser request, three parallel upstream calls, partial results allowed.
async function accountScreen() {
const names = Object.keys(adapters);
const settled = await Promise.allSettled(names.map((n) => adapters[n]()));
const panels = {};
settled.forEach((s, i) => {
// Only UpstreamError is a normalized failure. A timeout (DOMException) or a refused connection (TypeError) is not,
// and a DOMException has its own numeric `code` (23 for a timeout), so check the type instead of reading `.code`.
const e = s.reason;
panels[names[i]] = s.status === 'fulfilled'
? { status: 'ok', ...s.value }
: { status: 'error', error: e instanceof UpstreamError
? { code: e.code, message: `${names[i]} service failed (HTTP ${e.status})`, retryable: e.retryable } // e.message (the upstream text) stays server-side, for logs
: { code: 'UNAVAILABLE', message: 'upstream did not answer', retryable: true } };
});
return panels;
}
console.log('--- all upstreams healthy ---');
console.log(JSON.stringify(await accountScreen()));
console.log('--- page 2 of orders through the same normalized cursor ---');
console.log(JSON.stringify(await adapters.orders('3')));
console.log('--- invoices service down ---');
cMode = 'down';
const degraded = await accountScreen();
console.log(JSON.stringify({ orders: degraded.orders.status, tickets: degraded.tickets.status, invoices: degraded.invoices }));
console.log('--- invoices service hangs: the 500 ms deadline fires ---');
cMode = 'hang';
const t0 = Date.now();
const hung = await accountScreen();
console.log(JSON.stringify({ orders: hung.orders.status, invoices: hung.invoices }), 'waited under 1 s:', Date.now() - t0 < 1000);
console.log('--- wrong credential on service A: the thrown error keeps the upstream detail for server logs ---');
try { await call('orders', `${url(A)}/orders`, { authorization: 'Bearer nope' }); } catch (e) { console.log(e.source, e.status, e.code, e.message, 'retryable=' + e.retryable); }
[A, B, C].forEach((s) => { s.closeAllConnections(); s.close(); });
It prints:
--- all upstreams healthy ---
{"orders":{"status":"ok","items":[{"id":"100","amount":10},{"id":"101","amount":20},{"id":"102","amount":30}],"nextCursor":"3"},"tickets":{"status":"ok","items":[{"id":"t0","title":"Issue 0"},{"id":"t1","title":"Issue 1"}],"nextCursor":"2"},"invoices":{"status":"ok","items":[{"id":"9000","due":0},{"id":"9001","due":5}],"nextCursor":"2"}}
--- page 2 of orders through the same normalized cursor ---
{"items":[{"id":"103","amount":40},{"id":"104","amount":50},{"id":"105","amount":60}],"nextCursor":"6"}
--- invoices service down ---
{"orders":"ok","tickets":"ok","invoices":{"status":"error","error":{"code":"UPSTREAM_503","message":"invoices service failed (HTTP 503)","retryable":true}}}
--- invoices service hangs: the 500 ms deadline fires ---
{"orders":"ok","invoices":{"status":"error","error":{"code":"UNAVAILABLE","message":"upstream did not answer","retryable":true}}} waited under 1 s: true
--- wrong credential on service A: the thrown error keeps the upstream detail for server logs ---
orders 401 UPSTREAM_401 bad token retryable=false
Reading the code: AbortSignal.timeout(500) gives each upstream call a signal that aborts the fetch after 500 ms (MDN documents the abort reason as a TimeoutError), so a hung service cannot hold the screen. Promise.allSettled waits for all three adapter promises and returns one {status: 'fulfilled' | 'rejected'} entry per input, in input order, without rejecting itself when one input fails; that is why one dead service becomes one error panel instead of a failed screen. Only an UpstreamError is a normalized failure. A timeout rejects with a DOMException and a refused connection with a TypeError; neither is an UpstreamError, so the screen function checks the type with instanceof and labels them UNAVAILABLE, retryable: true, with a fixed message so no raw internals reach the UI. Reading reason.code instead would be a bug: a timeout's DOMException carries the legacy numeric code 23, which would leak into the panel as "code":23.
Reading the output: the screen came back from one function call with three panels, each carrying its own status. With service C returning 503 (its body, pool exhausted on db-7 (10.0.3.9), is internal detail), orders and tickets are still ok and invoices carries a normalized, retryable error whose message is the BFF's own invoices service failed (HTTP 503); the upstream text does not reach the panel. With service C hanging instead, the 500 ms deadline fires and the panel comes back as UNAVAILABLE in well under a second while orders stays ok. A wrong credential on service A (401) is an UpstreamError with retryable=false, because a client retry cannot fix a bad token; the last line prints bad token, the upstream detail that stays on the server-side error for logging, while the screen function would give the panel the BFF's own message. The normalized cursor for orders ("3") is the BFF's own opaque token; the UI never learns it is an offset.
When pagination crosses services
Each panel paginates itself, so no cross-service ordering is needed. If a screen needs one merged, sorted list across services, the BFF fetches a page from each, merges, and returns a cursor that encodes every source's position. Do that only when the product needs it: it multiplies upstream calls per page and makes the cursor fragile if any source reorders.
When to normalize in the frontend instead
Choose frontend normalization when all of these hold:
- The screen reads one service, so there is nothing to aggregate.
- The service needs no secret the browser cannot hold (public data, or the user's own login cookie where the browser and the service share a site, so the browser attaches the cookie itself and no secret sits in page JavaScript; this is different from a service credential such as C's session above).
- The difference is presentational: sorting, grouping or formatting data the UI already has, or interaction state such as an optimistic list update (showing a newly added row immediately, before the server has confirmed it).
- The BFF would add a hop and an owner for no gain, for example a prototype or a team without capacity to run one more service.
Anything that needs a secret, a join, or a unified error contract across services goes in the BFF.
Trade-offs and pitfalls
- The BFF is a new single point of failure for the web app. Mitigate with deadlines per upstream, partial responses (as shown), and health checks per adapter.
- Adapters are the part that rots: when service B changes its error format the BFF breaks. Cover each adapter with contract tests (tests that feed the adapter a recorded or fake copy of the service's reply format and fail when the format changes), as the fake upstreams here do in miniature.
- Keep the BFF thin. When a feature request starts with "the BFF should decide", check whether the rule belongs in a service.
- Do not leak adapter differences through the contract: a panel field called
nextOffsetin one panel andnextin another defeats the point.
Tell me about a time you worked with a cross-functional team. What was your role, and what made the collaboration succeed or struggle?
Sample Answer
Direct answer
Pick a project that genuinely needed more than one function, and be specific about two things: what YOU owned (not what 'the team' did), and the one concrete mechanism that determined whether the collaboration worked, such as a shared definition of done, a clear handoff point, or clarity on who decided what when opinions differed. Vague answers ('we communicated well') sound rehearsed; specific answers sound lived-in.
What the story needs to show
Your specific contribution. Interviewers are listening for what you personally decided or built, distinct from what your collaborators did. If every sentence is 'we', the interviewer cannot tell what you'd do differently on the next team.
A mechanism-level explanation. Organize the story around one of three lenses:
- Shared goal: did every function agree on what 'done' looked like and how success would be measured, or was each function quietly optimizing for its own definition?
- Interface or handoff: was there a clear point where work crossed from one function to another, and was that point actually defined, or did people guess?
- Decision rights: when functions disagreed, was it clear whose call it was, or did disagreement just stall until someone got tired of arguing?
Honesty if it's a struggle story. The question explicitly allows 'succeed or struggle'. A good struggle story ends on what you changed about the collaboration, not on who was at fault.
Worked example
Situation: [your team] needed to deliver [a feature or initiative] that required real work from [Team A, for example a design or research function] and [Team B, for example a data or infra function], against a fixed external date.
Task: your role was the one connecting the three groups, for example owning the shape of the interface between design and engineering, or owning how data requirements got translated into a schema.
Action: early on, each function had a different idea of what 'done' meant for their piece, which caused rework when the pieces met. You wrote a short one-page agreement naming the shared definition of done and who would sign off on each handoff, and used it to resolve the next two disagreements without a meeting.
Result: the project shipped on the revised date, and the agreement itself became something the group reused on the next cross-functional piece of work, which is the real marker of a story about redesigning the collaboration rather than just pushing through it.
To make that skeleton concrete rather than a fill-in-the-blank: picture a checkout redesign that needed real work from the design function and the payments engineering function, against a fixed external date tied to a promotional campaign launch. The specific disagreement was about what 'done' meant for the new payment-method selector: design considered the screen done once every state (loading, error, empty) matched the approved mockups pixel-for-pixel, while payments engineering considered it done once the integration correctly handled every payment-provider response code, even ones with no mockup drawn yet. That mismatch caused two rounds of rework when a payment-provider error state shipped without a design pass. The one-page agreement that resolved it included this line: 'A screen is done when it matches an approved mockup for every state the payments API can return, and any new state discovered after mockups are drawn triggers a joint 15-minute review before either side builds it.' That single sentence is what let the two functions stop re-litigating 'done' every time a new edge case appeared, and both sides signed off on it before the next round of work began.
Trade-offs and pitfalls
- A generic 'we all communicated well' answer with no mechanism is the single most common weak version of this story, avoid it.
- Over-crediting the team at the expense of your own specific contribution leaves the interviewer unable to evaluate you.
- If you pick a struggle story, resist framing it as the other function's fault. The senior version of this answer explains what you changed about how the groups worked together, not who dropped the ball.
- The strongest answers show you redesigning a structure (a handoff, a shared definition, a decision rule), not just working harder inside a broken one.
You need to ensure the checkout flow is robust across edge cases (payment provider failures, slow networks, multi-tab use, partial failures). Propose a balanced test suite across unit, integration, and E2E tests, listing specific test cases for edge behaviors, test data strategies, decisions for mocking versus using sandbox endpoints, and techniques to reduce E2E flakiness.
Sample Answer
Direct answer
A robust test suite for a checkout flow needs three layers with genuinely different jobs, not the same edge cases repeated at three levels: unit tests pin the exact logic of individual failure-handling decisions, integration tests verify the interaction between the client and the payment provider's contract (including sandbox behavior), and end-to-end (E2E) tests verify the small number of full user journeys that actually matter (a payment failure mid-flow, a multi-tab conflict, an interrupted network). Getting the split right, and being deliberate about mocking versus real sandbox endpoints, is what keeps this suite fast and trustworthy instead of slow and flaky.
Structured elaboration
| Layer | What it owns | Specific edge-case tests |
|---|---|---|
| Unit | Pure logic: given a specific provider response or error code, what does the checkout state machine decide to do next | Payment provider returns a declined-card error code vs. a network-timeout error code (these must route to different UI states, not one generic "payment failed" message); a duplicate submit is prevented by disabling the submit control the instant a request starts, tested by simulating two rapid submit events and asserting only one request fires |
| Integration | The real contract between the client code and the payment provider's actual API (application programming interface) shape, run against the provider's sandbox environment, not a hand-written mock of it | A sandbox-triggered decline response is parsed into the correct internal error type; a sandbox-triggered slow response (most providers' sandboxes support an artificial-delay test card or flag) is handled by the timeout logic without the UI hanging indefinitely; the client's idempotency-key header is actually present and correctly formed on a real request, which a hand-written mock cannot verify since it never sees the real serialized request |
| End-to-end | The handful of full user journeys where the FAILURE is the point, exercised through the real UI | Multi-tab: the same cart open in two tabs, one tab completes checkout, and the second tab's stale checkout attempt is rejected (or gracefully informed the order already completed) rather than double-charging; slow network: checkout submitted on a throttled connection shows an appropriate pending state rather than appearing to hang or allowing a second submit; partial failure: payment succeeds but the confirmation page fails to load, and reloading or returning to the site does not re-trigger payment |
Test data strategy: use the payment provider's own documented test card numbers and test scenarios for the sandbox tier (nearly every major provider publishes specific card numbers that deterministically trigger a decline, an insufficient-funds error, or a timeout), rather than inventing arbitrary fake numbers whose behavior against the real sandbox is unverified. For the E2E tier, seed a dedicated test account and cart state per test run so tests are independent and repeatable, rather than sharing mutable state across test runs.
Mocking vs. sandbox decision: mock the payment provider only at the unit-test layer, where the goal is to test the CLIENT's own decision logic in isolation and a real network call would only slow the test down without adding coverage of anything the client controls. Use the real sandbox at the integration layer specifically because that is where the client's actual serialized requests and the provider's actual response shapes need to agree, a hand-rolled mock of the provider's API can silently drift from the real contract as the provider's API evolves, passing tests against a mock that no longer matches reality.
Optimistic UI update edge cases from WebSocket message delivery: checkout flows that show optimistic UI state (e.g. "processing", then flipping to "confirmed") driven by WebSocket (a persistent, bidirectional connection protocol) events from the backend must handle messages arriving out of order or duplicated, both of which a plain network is free to do. A payment_confirmed event arriving before its own payment_processing event (reordering) must not leave the UI stuck showing "processing" forever once the actual final state has already arrived; the fix is applying incoming events against a state machine keyed by the event's own sequence number or timestamp, not by arrival order, which is the identical failure mode a payment gateway's own server-side webhooks produce and must be tested the same way. A payment provider delivers webhook events (for example charge.succeeded, charge.refunded) with at-least-once delivery: it retries with backoff whenever your endpoint does not answer with a 2xx response quickly enough, and that retry can arrive well after a later event that was delivered successfully on the first attempt. Concretely: your server receives a charge.refunded webhook (the provider's own event timestamp created=1005) and applies it at real time T=2; then, at real time T=30, a retried delivery of an earlier charge.succeeded webhook (created=1000, originally sent at T=0 but not acknowledged in time) finally arrives. A handler that applies whichever webhook it physically received last would incorrectly revert the charge back to "succeeded" after it was already correctly refunded, even though created=1000 is objectively the older event. The fix mirrors the client-side WebSocket case above: key state transitions off the provider's own event timestamp (or an explicit monotonic sequence or version field most gateways include), not off HTTP arrival order. Store the highest created value already applied per resource, and treat any incoming event whose created is less than or equal to that stored value as a no-op, regardless of when the HTTP request physically arrives. This needs its own explicit test case, webhook retried out of order: Input, two webhook payloads for the same resource, created=1000 type charge.succeeded and created=1005 type charge.refunded. Sequence: deliver created=1005 first (applied normally), then deliver created=1000 second (simulating the provider's retry). Expected output: the final stored state is "refunded" (from the created=1005 event), not "succeeded"; the late-arriving created=1000 event is detected as older than what is already applied and becomes a no-op.
A duplicated payment_confirmed event (the same event delivered twice, which most WebSocket reconnect-and-replay logic can produce) must be a no-op the second time, tested by feeding the same event object to the handler twice and asserting the UI state and any downstream side effect (e.g. an analytics ping) only fire once.
Trade-offs and pitfalls
The most common wrong turn is pushing every edge case to the E2E layer because "that's what really happens in production," which produces a slow, flaky suite that re-tests the same client-side decision logic dozens of times through a full browser instead of once at the unit layer. A second pitfall is mocking the payment provider at the integration layer too, which feels faster but stops catching provider API drift entirely, defeating the actual purpose of having an integration layer. On flakiness specifically, at the test-DESIGN level (not diagnosis or quarantine, which is a separate concern from writing the tests in the first place): avoid asserting on wall-clock-dependent intermediate states, pin any time-based logic behind an injectable clock rather than relying on real elapsed time in a test, and assert on the final, stable state reached rather than a transient one that a slow CI (continuous integration) runner might race past.
Your event handler is a class method and this is undefined when the browser calls it. Explain why, then show the safe patterns for passing methods as callbacks to listeners and timers, and how to remove those listeners later.
Sample Answer
Direct answer
this is decided by how a function is called, not where it was written. A class method called as instance.method() gets the instance, but when you hand instance.method to a listener, a timer or any code that calls it as a plain function, the connection to the instance is gone: this becomes whatever the caller supplies (the element for a DOM listener, a Timeout object for a Node timer, window for a browser timer), or undefined for a bare call f(), because class bodies are always strict mode. Either way this.count no longer reaches your instance. The safe patterns are: an arrow-function class field (or an arrow wrapper), bind once and keep the result, or passing an object with a handleEvent method (a standard DOM feature: addEventListener accepts an object instead of a function and, when the event fires, calls that object's handleEvent method with this set to the object). To remove a listener later you must pass the exact same function reference, or register it with an AbortController signal and abort once. Timers are removed with clearTimeout or clearInterval using the id you stored.
Why this is lost
button.addEventListener('click', obj.method) passes only the function object. The class method itself does not remember obj; the receiver is chosen at call time by whoever invokes it. Two common outcomes:
- Browser DOM events: the browser calls a regular function listener with
thisset to the element the listener is attached to (event.currentTarget), per MDN. So the method runs, butthisis the button, andthis.countis a property of the button, not your instance. The run below showsthisis the button. Node'sEventEmitter(an object that stores callbacks and invokes them itself) behaves the same way with a different receiver: it calls each listener withthisset to the emitter, soemitter.on('x', obj.method)also runs the method with the wrongthis(the emitter, notobj), and again no error is raised. - Code that calls the function bare (frameworks that call handlers as
handler(event), a destructured methodconst { increment } = counter, a library callback): there is no receiver, and because class code is strict,thisisundefined. The run below throws.
React class components are the classic case of the second kind, which is why they needed this.handleClick = this.handleClick.bind(this) in the constructor.
Safe patterns, and removing listeners
The harness first. JSDOM builds a fake browser page inside Node, window is that page's global object, and click() fires a click by calling button.dispatchEvent(new window.Event('click')), which runs every click listener synchronously. class Probe exists only to record what this is when the DOM calls a plain method: method() stores its this in seen, and seen === button prints true because the DOM sets this to the element, not to the Probe instance p.
// demo21.mjs
import { JSDOM } from 'jsdom';
const { window } = new JSDOM('<button id="b">go</button>');
const button = window.document.getElementById('b');
const click = () => button.dispatchEvent(new window.Event('click'));
const tryLog = (label, fn) => {
try { console.log(label.padEnd(30), fn()); }
catch (e) { console.log(label.padEnd(30), e.constructor.name + ':', e.message); }
};
class Counter {
count = 0;
// 1. plain method: this depends on the caller
increment() { this.count += 1; return this.count; }
// 2. arrow class field: one bound function per instance
incrementArrow = () => { this.count += 1; return this.count; };
// 3. handleEvent: the object itself is the listener
handleEvent(event) { this.count += 1; return event.type + ' ' + this.count; }
}
// What the plain method sees as this
const c = new Counter();
let seen;
class Probe { id = 'probe'; method() { seen = this; } }
const p = new Probe();
button.addEventListener('click', p.method);
click();
console.log('listener this is the button:', seen === button);
button.removeEventListener('click', p.method);
const { increment } = c; // detach, like passing it to code that calls it bare
tryLog('detached increment()', () => increment());
// Safe patterns
const arrow = new Counter();
button.addEventListener('click', arrow.incrementArrow);
click(); click();
console.log('arrow field after 2 clicks:', arrow.count);
button.removeEventListener('click', arrow.incrementArrow); // same reference: it works
click();
console.log('arrow field after removal:', arrow.count);
const he = new Counter();
button.addEventListener('click', he); // object with handleEvent
click();
button.removeEventListener('click', he);
click();
console.log('handleEvent after remove:', he.count);
// Pitfall: bind creates a NEW function each time
const b = new Counter();
button.addEventListener('click', b.increment.bind(b));
button.removeEventListener('click', b.increment.bind(b)); // different function: nothing removed
click();
console.log('bind-inline remove, count:', b.count, '(listener still active)');
// AbortController removes everything registered with its signal
const ac = new window.AbortController();
const d = new Counter();
button.addEventListener('click', () => d.increment(), { signal: ac.signal });
button.addEventListener('click', () => d.increment(), { signal: ac.signal });
click();
ac.abort();
click();
console.log('AbortController count:', d.count, '(two listeners ran once, then both removed)');
// Timers: store the id and clear it
class Ticker {
n = 0;
tick = () => { this.n += 1; };
start() { this.id = setInterval(this.tick, 5); }
stop() { clearInterval(this.id); }
}
const t = new Ticker();
t.start();
await new Promise((r) => setTimeout(r, 40));
t.stop();
const after = t.n;
await new Promise((r) => setTimeout(r, 40));
console.log('ticker advanced, then stopped:', after > 0, t.n === after);
Run in a node:22 container with jsdom (a simulated browser DOM), it prints:
listener this is the button: true
detached increment() TypeError: Cannot read properties of undefined (reading 'count')
arrow field after 2 clicks: 2
arrow field after removal: 2
handleEvent after remove: 1
bind-inline remove, count: 1 (listener still active)
AbortController count: 2 (two listeners ran once, then both removed)
ticker advanced, then stopped: true true
Choosing a pattern
| Pattern | How it works | Cost and catch |
|---|---|---|
Arrow class field handle = () => {...} | Arrow functions take this from the surrounding scope, which in a class field is the instance | One function per instance (not shared on the prototype), so large lists of instances use more memory; the method cannot be overridden through super.handle (a subclass's super.handle() looks the method up on the parent's prototype, and an arrow field is not there: it is an own property of each instance) |
this.handle = this.handle.bind(this) in the constructor | bind returns a new function with this fixed | Same per-instance cost; keeps a prototype method for subclasses; the stored reference is what you remove later |
Wrapper (e) => this.handle(e) | Arrow closes over this; a regular call restores the receiver | Anonymous: you must store it in a variable or use a signal to remove it |
addEventListener('click', this) with handleEvent | The object itself is the listener, and this inside handleEvent is that object | One handler per object, so switch on event.type for several events; removal passes the object itself |
Recommendation: default to the arrow-function field for handlers you register, and use an AbortController signal when a component registers several listeners that all die together. Choose handleEvent if one object handles many event types.
Removing listeners and timers
removeEventListenermatches on type, the listener function (or object) and the capture flag (thecaptureoption ofaddEventListener, which decides whether the listener runs while the event travels down to the target, the capture phase, or on its way back up, the bubble phase). An inline arrow or a fresh.bind(this)is a new function, so removal silently does nothing (thebind-inlineline above).- Store the handler once (field or constructor) and pass that same reference to both calls.
{ signal }onaddEventListenerremoves the listener when the controller'sabort()runs: one call tears down any number of listeners, and it works for anonymous functions.setTimeoutandsetIntervalreturn an id; keep it (this.id) and callclearTimeoutorclearIntervalin your teardown method (stop,disconnectedCallback, an unmount hook).connectedCallbackanddisconnectedCallbackare the web component lifecycle hooks the browser calls when the element is inserted into or removed from the page. A forgotten interval keeps the instance reachable forever, because the timer holds the callback and the callback holdsthis.
Running the code
# folder with package.json {"type":"module"} and demo21.mjs
docker run --rm -v "$PWD":/w -w /w node:22 sh -c 'npm i --silent jsdom && node demo21.mjs'
You have 48 hours to test a new sign-up flow for accessibility issues. Outline how you would include participants with disabilities on short notice, describe key accommodations you would provide during sessions, and list three accessibility metrics or observations you would capture.
Sample Answer
Direct answer. Testing a new sign-up flow for accessibility with only 48 hours' notice means compressing the usual multi-week recruitment cycle into a rapid-response protocol: lean on an existing pre-vetted panel of assistive-technology users rather than starting recruitment from scratch, accept a smaller sample size than an ideal study would use, and be explicit with participants about the compressed timeline and what accommodations you can and can't arrange on short notice.
Including participants on short notice. Maintain a standing, pre-consented panel of assistive-technology users specifically for this kind of rapid-turnaround need, recruited and vetted in advance during normal timelines, so a 48-hour ask is "schedule 3 to 4 sessions with people already in the panel" rather than "find and vet participants from zero"; without a standing panel, the realistic fallback is a specialist recruiting agency that maintains its own accessibility-specific panel, accepting a premium cost for the speed.
Accommodations on a compressed timeline. Be upfront that some accommodations (interpreter services, specific physical-space requirements) may not be arrangeable in 48 hours, and scope the session to remote/asynchronous formats where possible, which are generally faster to arrange than in-person sessions requiring physical accessibility logistics.
What to prioritize testing. With limited sessions, focus specifically on the highest-risk, most novel parts of the new flow (anything genuinely custom, like a non-standard multi-step progress indicator) rather than attempting comprehensive coverage of the whole flow, since a rushed study spread too thin catches less than a focused one.
Metrics and observations to capture. Three concrete things to record even in a compressed 3 to 4 session study: (1) task completion per participant on the sign-up flow, noting the SPECIFIC step where any failure or workaround occurred, not just a pass/fail tally, since the step-level location is what makes the finding actionable; (2) time-on-task and number of navigation attempts (repeated tabbing, repeated screen-reader re-reads of the same region) as a proxy for friction even when the task technically completes, since a participant who eventually succeeds after struggling still surfaces a real defect; (3) direct verbatim quotes or specific confusion points from the think-aloud narration, especially anywhere a participant's mental model of what just happened diverged from what the interface intended to communicate. Log all three per participant so the compressed sample size doesn't also lose its diagnostic detail.
Trade-offs and pitfalls. A 48-hour study is a real compromise, not equivalent to a properly-resourced study, and should be explicitly labeled as such in the findings report (a rapid, directional signal, not a comprehensive audit) so stakeholders don't treat a rushed 3-participant session as if it had the same confidence as a proper 8 to 10 participant study across the full range of relevant conditions; the honest response to being asked for this under-resourced turnaround is often also to flag that the timeline itself is a risk worth escalating, not just to silently comply and produce a study whose limitations go unstated.
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