Microsoft Frontend Developer (Junior Level) Interview Preparation Guide
Microsoft's frontend developer interview process for junior-level candidates typically consists of an initial recruiter screening, followed by 1-2 technical phone rounds, and 4 onsite interview rounds spanning multiple days. The process evaluates JavaScript and React proficiency, fundamental algorithmic problem-solving, UI component design, system design thinking, and cultural fit. Based on documented interview experiences, the process emphasizes hands-on coding, real-world UI implementation challenges, and behavioral assessment aligned with Microsoft's leadership principles.[2]
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with a Microsoft recruiter to assess your background, motivation, and fit for the role. This round confirms basic qualifications, discusses your experience with frontend technologies, and evaluates your interest in Microsoft. The recruiter may ask about salary expectations, availability, and willingness to relocate if needed.
Tips & Advice
Be authentic and enthusiastic about frontend development. Have a clear 2-3 minute pitch about your experience, the technologies you work with, and why you're interested in Microsoft. Ask thoughtful questions about the team and role to demonstrate genuine interest. Mention any experience with React, as it's heavily used at Microsoft. Keep answers concise but substantive.
Focus Topics
Motivation and Microsoft Fit
Articulate why you're interested in Microsoft specifically, what appeals to you about the company's mission, products, or culture, and how this role aligns with your career goals.
Practice Interview
Study Questions
React and Modern Framework Familiarity
Brief overview of your experience with React or similar frameworks—projects you've built, libraries you've used, and learning enthusiasm for evolving technologies.
Practice Interview
Study Questions
Professional Background and Relevant Experience
Clearly articulate your 1-2 years of frontend development experience, key projects you've contributed to, and technologies you've worked with (HTML, CSS, JavaScript, React, etc.).
Practice Interview
Study Questions
Technical Phone Screen
What to Expect
A 45-60 minute technical interview with a Microsoft engineer conducted over video/phone. You'll be given a practical UI coding challenge to implement in a shared code editor (typically using vanilla JavaScript, HTML, and CSS). The challenge is designed to assess fundamental DOM manipulation, JavaScript knowledge, and problem-solving approach. Examples from real Microsoft interviews include building interactive components like number pads or form validations. You may be asked to explain your code, handle edge cases, and optimize for performance or accessibility.
Tips & Advice
Start by clarifying requirements and asking clarifying questions before coding. Write clean, readable code with proper variable naming and comments. Think aloud to show your problem-solving process. Focus on correctness first, then optimize. Test edge cases and discuss accessibility considerations. If you get stuck, explain your thinking and ask for hints—interviewers appreciate honest communication over silent struggle. Avoid jumping straight to complex solutions; build incrementally.
Focus Topics
CSS and Responsive Design Basics
Understanding CSS layout (flexbox, grid basics), positioning, styling interactive states (hover, focus), and ensuring components work across screen sizes.
Practice Interview
Study Questions
Code Organization and Readability
Writing semantic HTML, maintaining clean CSS structure, organizing JavaScript logic into functions, using meaningful variable names, and keeping code maintainable for team collaboration.
Practice Interview
Study Questions
Problem-Solving and Communication
Thinking aloud during implementation, asking clarifying questions, discussing trade-offs, acknowledging constraints, and explaining your approach step-by-step.
Practice Interview
Study Questions
DOM Manipulation and JavaScript Fundamentals
Proficiency in vanilla JavaScript DOM operations (querySelector, addEventListener, createElement, innerHTML, classList), event handling, and basic data structure manipulation without relying on frameworks.
Practice Interview
Study Questions
Event Handling and User Interactivity
Understanding event delegation, event propagation, capturing different user interactions (click, keydown, input), and implementing responsive UI behavior based on user actions.
Practice Interview
Study Questions
Onsite Round 1: React Component Implementation
What to Expect
A 45-60 minute technical interview conducted onsite (or virtually if remote) focusing on React component development. You'll build a functional React component with state management, handling user interactions, and integrating with basic data structures. Real examples from Microsoft interviews include building a to-do application with add/remove/edit functionality or interactive UI components. The focus is on demonstrating React fundamentals, component lifecycle understanding, hooks usage (if applicable), and the ability to manage component state effectively.
Tips & Advice
Clarify requirements thoroughly before starting. Structure your component thoughtfully—consider state management, component hierarchy, and separation of concerns. Use functional components with hooks (useState, useEffect) as these are modern React standards at Microsoft. Handle edge cases like empty states or loading states. Write tests or discuss testability of your component. Be prepared to refactor or optimize based on feedback. Discuss performance considerations and when you might use React.memo or useCallback.
Focus Topics
Event Handling in React
Handling synthetic events in React, binding event handlers, passing arguments to handlers, and understanding event propagation in the React ecosystem.
Practice Interview
Study Questions
Conditional Rendering and List Handling
Implementing conditional rendering patterns, rendering lists with keys, filtering and mapping data, and handling dynamic UI updates.
Practice Interview
Study Questions
Component Composition and Reusability
Building reusable, composable components, prop types/validation, and organizing component hierarchies for maintainability and scalability.
Practice Interview
Study Questions
React Functional Components and Hooks
Proficiency with functional components, useState for state management, useEffect for side effects, and understanding the dependency array. Knowledge of custom hooks for reusable logic.
Practice Interview
Study Questions
State Management in React
Understanding when and how to lift state up, passing props effectively, handling form state, and managing data flow between parent and child components.
Practice Interview
Study Questions
Onsite Round 2: Algorithmic Coding
What to Expect
A 45-60 minute technical interview focused on algorithmic problem-solving using JavaScript. You'll be asked to solve LeetCode-style problems typically in the easy-to-medium range. Based on Microsoft interview data, problems may include array manipulation, string operations, or logic puzzles. The focus is on your ability to think through problems, apply appropriate data structures and algorithms, optimize solutions, and communicate your approach. You'll use a shared code editor and may need to write test cases or discuss complexity analysis.
Tips & Advice
Read the problem carefully and clarify edge cases before coding. Start with a brute-force approach, then optimize. Explain your time and space complexity. Write clean, readable code with proper variable names. Test with multiple examples, including edge cases (empty input, single element, negative numbers, etc.). If you're stuck, think aloud about potential approaches—interviewers may provide hints. Practice common algorithms like sorting, searching, and basic graph traversal beforehand. Remember: correctness is more important than optimization for junior-level candidates, but aim for reasonable efficiency.
Focus Topics
JavaScript-Specific Problem-Solving
Leveraging JavaScript APIs and idioms for efficient solutions, understanding prototypes for complex operations, and avoiding common JavaScript pitfalls.
Practice Interview
Study Questions
Time and Space Complexity Analysis
Calculating Big O time and space complexity for solutions, identifying bottlenecks, and discussing trade-offs between optimization approaches.
Practice Interview
Study Questions
Problem-Solving Methodology
Systematic approach to coding problems: clarify requirements, identify examples, develop approach, code, test, optimize. Communicating each step clearly.
Practice Interview
Study Questions
Basic Data Structures
Understanding and applying stacks, queues, linked lists, and hash maps to solve problems efficiently. Knowing when to use each structure.
Practice Interview
Study Questions
Arrays and String Manipulation
Solving problems involving array operations (sorting, searching, filtering), string processing, two-pointer techniques, and sliding window approaches.
Practice Interview
Study Questions
Onsite Round 3: UI System Design and Architecture
What to Expect
A 45-60 minute discussion-based interview focused on system design thinking for frontend architecture. You'll be asked to design a UI component, feature, or small application—for example, building an emoji autocomplete feature, a notification system, or implementing a part of a chat interface. The interviewer will probe your design decisions, scalability considerations, performance optimization, API integration patterns, and component architecture. This round assesses your ability to think beyond immediate implementation and consider the broader system, based on real Microsoft interviews that involve designing features similar to Microsoft Teams components.
Tips & Advice
Start by clarifying requirements and constraints (performance goals, scale, supported browsers, accessibility requirements). Draw diagrams or outline your component structure. Discuss trade-offs in your design decisions—why you chose certain approaches over others. Consider API design and contracts with backend services. Think about performance (lazy loading, caching, debouncing). Discuss scalability: how your design handles growing data or users. Address accessibility and cross-browser compatibility. Be open to feedback and show flexibility in adjusting your design based on interviewer suggestions. It's a conversation, not a presentation.
Focus Topics
Accessibility and Cross-Browser Considerations
Designing with accessibility in mind (ARIA, semantic HTML, keyboard navigation), ensuring cross-browser compatibility, and testing strategies for these concerns.
Practice Interview
Study Questions
API Integration and Data Flow
Designing component APIs, integrating with REST or GraphQL backends, handling async data loading, error states, and discussing data fetching strategies (loading, caching, refetching).
Practice Interview
Study Questions
Performance Optimization Techniques
Discussing techniques like lazy loading, code splitting, memoization, debouncing/throttling, caching strategies, and identifying common performance bottlenecks in frontend applications.
Practice Interview
Study Questions
Component Architecture and Hierarchy Design
Planning component structure, identifying reusable vs. container components, managing data flow, and designing APIs/props between components for maintainability and scalability.
Practice Interview
Study Questions
State Management Strategy
Choosing appropriate state management approaches (local component state, context, external state management), discussing trade-offs for different scenarios, and managing data flow in complex UIs.
Practice Interview
Study Questions
Onsite Round 4: Behavioral Interview and Hiring Manager Discussion
What to Expect
A 45-60 minute behavioral and cultural fit interview, typically with a senior engineer, team lead, or hiring manager. This round assesses your alignment with Microsoft's leadership principles, teamwork abilities, communication skills, learning mindset, and career motivation. You'll discuss past experiences using the STAR method (Situation, Task, Action, Result), how you handle challenges, conflicts, feedback, and your approach to continuous learning. The interviewer will also discuss the role, team dynamics, expectations, and answer your questions about working at Microsoft.
Tips & Advice
Prepare 5-6 detailed STAR stories covering: overcoming a technical challenge, collaborating in a team, handling feedback, learning something new, dealing with ambiguity, and a failure/mistake you learned from. Be specific with details and quantifiable outcomes where possible. Connect your examples to Microsoft's leadership principles when relevant. Show genuine enthusiasm for growth, learning, and contributing to team success. Ask thoughtful questions about the team, role expectations, and company culture. Be authentic—Microsoft values genuine, collaborative people over polished responses. Listen carefully to what the interviewer says about the role and team, as this helps you gauge fit and prepare intelligent follow-up questions.
Focus Topics
Communication and Documentation
Ability to explain technical decisions clearly to both technical and non-technical stakeholders, document code and decisions, and keep team informed of progress or blockers.
Practice Interview
Study Questions
Handling Feedback and Failure
Discuss how you respond to constructive criticism, learn from mistakes, iterate on solutions based on feedback, and maintain resilience during challenging projects.
Practice Interview
Study Questions
Problem-Solving Under Ambiguity
Share examples of handling unclear requirements, making decisions with incomplete information, asking clarifying questions, and iterating to find solutions.
Practice Interview
Study Questions
Teamwork and Collaboration
Demonstrate ability to work effectively with diverse team members (engineers, designers, product managers), resolve conflicts constructively, and contribute to team success beyond individual tasks.
Practice Interview
Study Questions
Learning and Growth Mindset
Show enthusiasm for continuous learning, adaptability to new technologies and frameworks, seeking feedback, and proactively improving skills. Discuss how you stay current with frontend trends.
Practice Interview
Study Questions
Frequently Asked Frontend Developer Interview Questions
Given a string, find the index of the first character that does not repeat anywhere else in it, or report that none exists. Do it in O(n) time, and discuss how a streaming variant (characters arriving one at a time, asked at any point) would change your approach.
Sample Answer
Direct answer
Count every character's frequency in one pass (a hash map or Counter), then make a second pass over the string returning the first character whose count is exactly 1. This is O(n) time and O(k) space, where k is the number of distinct characters. If the string arrives one character at a time and you must be able to answer "what's the first non-repeating character so far" at any point, keep a queue of once-seen candidates in arrival order and evict its front whenever that character's count rises above 1.
Structured elaboration
Two-pass approach, for a string you already have in full:
from collections import Counter
def first_non_repeated(s):
"""
Return first non-repeated character in s, or None if none exists.
Two-pass approach: O(n) time, O(k) space (k = distinct characters).
"""
if not s:
return None
counts = Counter(s)
for ch in s:
if counts[ch] == 1:
return ch
return None
Streaming variant. The two-pass approach needs the whole string up front. If characters arrive one at a time and a query can land at any point, you cannot afford to rescan everything seen so far on every query. Instead, maintain a frequency map alongside a queue (double-ended queue) of characters that are currently unique, in the order they first appeared:
from collections import deque
class StreamingFirstNonRepeated:
"""
Streaming variant: feed one character at a time via .push(ch) and query
.current() at any point without rescanning history. O(1) amortized time
per pushed character (each character enters and leaves the deque at most
once), O(k) space for k distinct characters seen so far.
"""
def __init__(self):
self.counts = {}
self.q = deque()
def push(self, ch):
self.counts[ch] = self.counts.get(ch, 0) + 1
if self.counts[ch] == 1:
self.q.append(ch)
while self.q and self.counts[self.q[0]] > 1:
self.q.popleft()
def current(self):
return self.q[0] if self.q else None
The queue's front is always the earliest-arrived character that is still unique, because any character that becomes non-unique gets evicted from the front the moment its count rises above 1 (it may sit behind the front briefly until it becomes the front, but it is removed by the time it would otherwise be reported).
Worked example
s = "swiss"
print(first_non_repeated(s))
tracker = StreamingFirstNonRepeated()
running = []
for ch in s:
running.append(ch)
tracker.push(ch)
print(''.join(running), '->', tracker.current())
Output:
w
s -> s
sw -> s
swi -> s
swis -> w
swiss -> w
The full-string answer is w, matching the streaming tracker's final answer. Along the way you can see the answer change: after "s", "sw", "swi" the answer is still s (unique so far); once the second s arrives ("swis") the tracker evicts s from the front and reports w; the final s in "swiss" doesn't change the answer since w is still unique.
Trade-offs & pitfalls
Key points
- The two-pass approach is the simplest correct solution when the full string is available; don't reach for the streaming version if you don't need "answer at any point in time" semantics, since it adds a queue and eviction logic for no benefit.
- The streaming approach never needs to rescan from the start, but it does need to keep counts for every distinct character seen so far, and the queue can (temporarily) hold characters that later get evicted, so peak memory is still O(k) not O(1).
- Multi-codepoint or combined Unicode characters (for example, accented characters built from a base character plus a combining mark) are treated as separate codepoints by both approaches; if the requirement is "first non-repeating user-visible character" rather than "first non-repeating codepoint," you would need a grapheme-aware library instead of iterating raw codepoints.
Complexity
- Two-pass: time O(n), space O(k).
- Streaming: O(1) amortized time per pushed character (each character is added to and removed from the queue at most once), space O(k) for the counts and queue combined.
Edge cases
- Empty string: both approaches return
None. - All characters repeated: both return
None(the two-pass loop finds no count-1 character; the streaming queue empties out). - Single character: trivially non-repeating, both return it.
Explain the difference between mutable and immutable string types in common languages (Python, Java, C++ std::string) and how that affects algorithm design for in-place vs copy-based operations, time complexity, and memory usage. Give examples where choosing one approach over the other matters in practice.
Sample Answer
Direct answer
In Python and Java, strings are immutable: every operation that looks like a modification, concatenation, replacing a character, actually allocates a new string object, leaving the original untouched. In C++, std::string is mutable by design: it supports true in-place modification of its own buffer. That single difference changes how you write efficient string-processing code: Python and Java favor building output through a mutable intermediate (a list of pieces, or Java's StringBuilder) and converting to a string once at the end, while C++ can often modify a std::string directly without ever needing that intermediate.
Structured elaboration
What mutable and immutable mean here
An immutable string type guarantees that once created, the sequence of characters it represents never changes. Any apparent edit, s = s + "x" in Python, s = s.concat("x") in Java, produces a brand new string object; the variable name is simply reassigned to point at it. A mutable string type, std::string in C++, or Java's StringBuilder/StringBuffer (which exist specifically because String itself is immutable), allows the underlying character buffer to be changed directly, without creating a new object each time.
| Language construct | Mutable? | True in-place edit possible? | Typical mutable companion |
|---|---|---|---|
Python str | No | No | build a list, ''.join(...) at the end |
Java String | No | No | StringBuilder / StringBuffer |
C++ std::string | Yes | Yes | itself |
Go string | No | No | strings.Builder |
Kotlin String | No | No | StringBuilder (same JVM story as Java) |
C (char* / array) | Yes (unless a literal) | Yes | itself, with manual bounds management |
How this affects algorithm design
For a problem like "reverse this string in place," C++ can genuinely reverse the existing std::string buffer with a two-pointer swap and zero extra allocation. The identical-looking task in Python or Java cannot touch the original string object at all, since it is immutable; the practical in-place technique is to convert to a mutable structure first, a list of characters in Python, a char[] or StringBuilder in Java, perform the two-pointer swap on THAT structure, and only build a new string from it at the very end. This is why coding-interview answers to "reverse a string in place" in Python conventionally operate on list(s): that satisfies the spirit of in-place swapping even though the original str object could never have been mutated directly.
Time complexity and memory usage
Because every "modification" of an immutable string allocates a new object sized to the result, repeated modification in a loop, appending a small piece to a string n times, costs O(n) time for a single append but can cost O(n^2) time in total across n iterations if done naively, since each append copies everything accumulated so far into the new object. A std::string or a StringBuilder/list-based accumulator instead grows its internal buffer with amortized doubling, giving O(n) total time cost for n appends, since only the buffer's OWN internal reallocation is doubling-based, not a full-string copy on every single append. The memory usage story mirrors the time complexity one: the immutable-string approach transiently holds BOTH the old and new copies at every step (peak memory proportional to the final size, plus churn from every discarded intermediate copy needing garbage collection), while the mutable-accumulator approach holds only the one growing buffer, at some points with a bit of unused reserved capacity from the last doubling.
Worked example
s = "hello"
before_id = id(s)
s = s + " world"
after_id = id(s)
print(before_id != after_id) # True: concatenation created a new object
lst = [1, 2, 3]
lst_id_before = id(lst)
lst.append(4)
lst_id_after = id(lst)
print(lst_id_before == lst_id_after) # True: append mutated the SAME object
Output:
True
True
The first check confirms that s + " world" really did allocate a new string object (the identity changes), demonstrating immutability directly rather than just asserting it. The second confirms the contrasting case: a Python list, which is mutable, keeps the same object identity across an in-place append. The equivalent contrast in C++ would show std::string::operator+= modifying the SAME underlying buffer (when capacity allows) rather than always allocating a new one, which is the concrete behavioral difference this question is asking about.
Trade-offs and pitfalls
A frequent mistake in interviews is claiming a Python or Java "in-place" string function actually mutates the original string object, when what really happened is the function returned a new string; the answer needs to be explicit about that distinction. Another is assuming C++'s mutability makes it strictly faster for all string work: C takes mutability further still, since a char*/array-backed string is always mutable at the byte level with no separate immutable type at all, but that control comes with none of the safety immutability provides elsewhere, buffer overruns and missing null terminators are a classic consequence. Go's string mirrors Python's model closely (immutable, with strings.Builder playing the accumulator role list+join plays in Python), and Kotlin's String is immutable for the same reason Java's is, since both compile to the same JVM string representation, so the same StringBuilder-based advice carries over unchanged. The practical lesson that generalizes across every one of these languages: whenever you need to build a string piece by piece in a loop, reach for the language's designated mutable-accumulator type rather than the plain immutable string type.
You are responsible for a system or feature that currently has little to no instrumentation, and something about it (a bug, an outage, or unclear behavior) needs to be understood right now. Under a tight time or budget constraint, how would you gather just enough signal to make a defensible call today, and how would you prioritize what to instrument going forward so this is not a problem next time?
Sample Answer
Direct answer
Matching the rigor of your evidence to the cost of being wrong, not maximizing data collection, is
the whole answer here. Ask three things fast: what decision does this signal need to support, what
is the cheapest proxy that is directionally correct even if imprecise, and what is the smallest
instrumentation change that gets that proxy today rather than next sprint.
Under time pressure with no instrumentation
If something needs an answer within a day or two and there's no logging in place, don't try to
build proper instrumentation first. Use whatever adjacent signal already exists for some other
purpose, server access logs, billing or usage records, an error-tracking tool set up for a
different reason, or even a manual sample, pulling fifty real examples and hand-reviewing them, to
get a directionally correct answer fast, and be explicit when reporting it that it's a rough
estimate, not a final number.
Under a budget constraint specifically
A budget constraint is a different pressure from a time constraint: you may have weeks, but can't
buy a new analytics tool or warehouse table. The answer leans on infrastructure already paid for,
application logs already emitted for debugging, an existing spreadsheet-based manual log an
operations team keeps, a support-ticket export, accepting slower turnaround rather than new spend.
When the spec itself defines no metrics
Before writing any code, define the minimum set of events that let you say "this sprint's work
shipped something real." For a new flow with no stated success metric, that minimum might be just
three events: flow started, flow completed, flow abandoned at a given step. That's enough to answer
"did this work" even before it can answer "why," and it's a far smaller lift than a full analytics
suite.
When the feature already shipped with nothing tracked
You can't go back in time, so the interim decision has to rest on proxies collected for other
purposes, server logs, database row-creation timestamps as a usage proxy, support-ticket volume
mentioning the feature, while proper forward-looking instrumentation gets added starting now. Be
explicit to stakeholders that the interim number is a backward-inferred proxy, not tracked data, so
they calibrate their confidence correctly, and state the date after which the number becomes
trustworthy on real data.
Applied to a scenario combining all four pressures
A team ships an in-app referral feature with no success metrics defined. Three weeks post-launch,
leadership asks in a Monday meeting whether it's working, wanting an answer for a board update two
days later, and there's no budget approved this quarter for a new analytics tool. With no
instrumented conversion funnel, the team pulls two things that already exist for free: a raw
database count of referral-code redemptions, and a manual sample of thirty support tickets
mentioning "referral" to gauge friction qualitatively. The answer delivered two days later: "119
referral codes were redeemed in the first three weeks, a real count from the database, against zero
specific complaints about the referral flow in a thirty-ticket sample, a rough qualitative signal,
not a precise satisfaction score; we don't yet have a true conversion rate because the flow's start
and abandon steps were never instrumented." That's honest, defensible, and useful, paired with a
one-sprint plan to add the three minimum events going forward, prioritized above lower-traffic
features specifically because referrals are likely to be asked about again at every future board
update.
Prioritizing instrumentation going forward
Once the immediate call is made, decide what to build permanently using the same risk-times-
frequency logic used elsewhere: instrument first whatever will be asked about repeatedly, a core
funnel step, a metric feeding a recurring business review, or whatever carries the highest cost if
you're caught blind again, and write that as a short ranked backlog rather than an open-ended "add
more logging" task.
Beyond data science
An SRE facing an outage on a legacy service with no tracing does the identical thing, using
adjacent signals like host-level CPU and network graphs or load-balancer logs to make a defensible
call in the moment, then adding proper tracing prioritized by which service will be asked about
again.
Explain the difference between registering an event handler with an inline attribute (e.g., <button onclick="...">), assigning to element.onclick = fn, and using element.addEventListener('click', fn). Describe the pros and cons of each approach and give an example scenario where addEventListener is clearly preferable.
Sample Answer
Direct answer
All three attach a function that runs when the element is clicked, but they differ in how many handlers you get, who can interfere, and what you can control. An inline attribute (<button onclick="save()">) is JavaScript source inside the HTML: one handler, a scope limited to global names plus the properties of the element, its form and the document, and it is blocked by a strict Content Security Policy (CSP, a response header that tells the browser which script sources to trust). The property (button.onclick = fn) is a single slot: assigning again replaces the previous function. addEventListener('click', fn) keeps a list, so any number of independent callers can add handlers, each can remove its own, and only this form accepts the capture, once, passive and signal options. Use addEventListener in application code. MDN recommends it and calls the HTML attributes bad practice.
Side-by-side
| Inline attribute | element.onclick = fn | addEventListener | |
|---|---|---|---|
| Handlers per event | One | One (a new assignment replaces the old) | Any number |
| Removal | Remove the attribute | Assign null | removeEventListener, a signal, or once |
| Options (capture, once, passive) | None | None | Yes |
| Scope of names in the code (which variables the code can see) | Global names (those on window), but the element's own, its form's and the document's properties shadow them (a bare id is the element's id); this is the element | A function with its own closure (it keeps access to the variables around where it was written) | A function with its own closure |
| Under a CSP that blocks inline script | Blocked | Works | Works |
| Typical downside | Mixes markup and logic; cannot reach module-scoped functions (functions declared inside a <script type="module">, which are private to that module unless exported) | Last writer wins, silently | Anonymous functions cannot be removed; duplicates are ignored only for the same function and options |
Measured on a real page
The page below is served by a small Node server (http.createServer answers every request with the same HTML string, adding the CSP header only for URLs that start with /csp; listen(0) picks a free port). It has button a with an inline handler, and button b where a property is assigned twice around two addEventListener calls, plus one function registered twice. Button c has an inline handler that calls a function declared in a <script type="module">. The server sends the page twice: once plainly and once with the header Content-Security-Policy: script-src 'self' 'unsafe-inline'; script-src-attr 'none'. The log records which handlers ran. A pageerror listener on the Playwright page collects uncaught JavaScript errors, which is how the error from button c is captured.
// handler_styles.mjs
import { chromium, firefox, webkit } from 'playwright';
import http from 'node:http';
const page_html = `<!doctype html><button id="a" onclick="hit('inline', this.id)">a</button>
<button id="b">b</button><button id="c" onclick="moduleOnly()">c</button>
<script type="module">function moduleOnly() { hit('module'); }</script><script>
var log = [];
function hit(k, extra) { log.push(k + (extra ? ':' + extra : '')); }
const b = document.getElementById('b');
b.onclick = () => hit('prop-1');
b.addEventListener('click', () => hit('listener-A'));
b.onclick = () => hit('prop-2'); // replaces prop-1; keeps prop-1's place in the order
b.addEventListener('click', () => hit('listener-B'));
function same() { hit('same'); }
b.addEventListener('click', same);
b.addEventListener('click', same); // identical callback + options: ignored
</script>`;
const server = http.createServer((req, res) => {
const csp = req.url.startsWith('/csp');
res.writeHead(200, { 'content-type': 'text/html', ...(csp ? { 'content-security-policy': "script-src 'self' 'unsafe-inline'; script-src-attr 'none'" } : {}) });
res.end(page_html);
}).listen(0);
const base = `http://127.0.0.1:${server.address().port}`;
for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
const browser = await type.launch();
const page = await browser.newPage();
await page.goto(base + '/plain');
const errors = [];
page.on('pageerror', (e) => errors.push(e.name));
await page.click('#a'); await page.click('#b'); await page.click('#c');
const plain = await page.evaluate(() => log.join(' '));
const csp = await browser.newPage();
await csp.goto(base + '/csp');
await csp.click('#a'); await csp.click('#b');
const blocked = await csp.evaluate(() => log.join(' '));
console.log(name, '| no CSP:', plain, '| error from #c:', errors.join(',') || 'none', '| script-src-attr none:', blocked);
await browser.close();
}
server.close();
chromium | no CSP: inline:a prop-2 listener-A listener-B same | error from #c: ReferenceError | script-src-attr none: prop-2 listener-A listener-B same
firefox | no CSP: inline:a prop-2 listener-A listener-B same | error from #c: ReferenceError | script-src-attr none: prop-2 listener-A listener-B same
webkit | no CSP: inline:a prop-2 listener-A listener-B same | error from #c: ReferenceError | script-src-attr none: prop-2 listener-A listener-B same
How to read the header first: script-src 'self' 'unsafe-inline' allows scripts from the same origin and inline <script> blocks ('unsafe-inline' is the keyword that permits inline script; the name warns that it removes a protection), while script-src-attr 'none' overrides that for inline event-handler attributes such as onclick="..." only, so they are refused even though inline script blocks stay allowed. That is why a is dead while the property and listener styles still run. How to read each line. In the plain page, clicking a logs inline:a, so the attribute ran with this as the button itself. For b, the log is prop-2 listener-A listener-B same: prop-1 never appears because the second assignment replaced it, and same appears once even though it was added twice, because an identical function with identical options is not added a second time (MDN documents this). prop-2 runs before listener-A even though it was assigned after it, because the property keeps the list position it got at its first assignment in all three engines. Button c throws a ReferenceError, because the module's function is not a global. Under the script-src-attr 'none' header the inline handler on a does nothing and the other two styles keep working, as MDN documents for that directive.
Pros and cons in plain terms
- Inline attribute. Pro: nothing to wire, visible right where the button is. Cons: one handler, no separation of markup and behaviour, the code is a string inside the markup, it can reach only global functions (and the element, form and document properties that shadow them), and a CSP can block it. A policy that forbids inline script is a normal hardening step (tightening security settings so less can go wrong), and an application that relies on inline handlers has two ways to keep them: loosen the policy to
'unsafe-inline', which also re-allows every injected inline script, or keepscript-src-attrrestrictive and allow only the known handler strings with the'unsafe-hashes'keyword plus thesha256-hash of each handler's exact source text (a stopgap while the templates are migrated toaddEventListener). Withscript-src-attr 'unsafe-hashes' 'sha256-<hash of hit('inline', this.id)>'in place of'none', the inline handler on buttonaran again in Chromium, Firefox and WebKit. - Property. Pro: short, handlers are plain functions, no CSP problem. Con: single slot. A widget library that sets
button.onclicksilently deletes the handler your page set earlier, and the reverse. addEventListener. Pros: several independent handlers, options, clean removal, works with delegation andAbortController. Con: you must keep the function reference (or use a signal) to remove it, and anonymous functions registered twice are two listeners.
A scenario where addEventListener is clearly right
A "Buy" button is clicked, and three unrelated pieces of code care: the cart module updates the count, an analytics module records the click, and an A/B-testing script (one that shows different page variants to different visitors to compare them) highlights the button. Each lives in its own file and ships at a different time. With onclick, whichever script runs last wins (last writer wins: each assignment overwrites the previous one) and the other two silently stop working. With addEventListener, each module adds its own handler and none knows about the others. When the cart module is torn down (for example, on a route change in a single-page app, a site that swaps views in place without full page loads) it removes only its own handler. Analytics can listen on document with { capture: true } so it still sees the click even if a handler on the button stops propagation.
Pitfalls
- Mixing styles on one element works, but the property occupies one position in the same list, so order can surprise you; pick one style per element.
- An anonymous function passed to
addEventListenercannot be removed later and is not recognised as a duplicate of an identical-looking one, so name any handler you may need to remove.
Running the code
mkdir demo && cd demo
echo '{"type":"module"}' > package.json
npm i playwright@1.48.2
npx playwright install chromium firefox webkit
# save the listing(s) above as handler_styles.mjs, then run:
node handler_styles.mjs
The printed output comes from runs in the mcr.microsoft.com/playwright:v1.48.2-jammy container, where the browsers are already installed and the install step is not needed. Playwright's WebKit build is the WebKit engine, not Safari itself.
How do you structure a short, time-boxed presentation so a live audience can follow it: what goes in the opening, how do you signal the shape of the talk as you move through it, and how do you close?
Sample Answer
Direct answer
Open by telling the audience what you're going to cover and why it matters to them, signpost explicitly as you move between sections so they always know where they are, and close by restating the key takeaway rather than just stopping.
Structured elaboration
- Opening: state the topic, why the audience should care (what decision or understanding this affects them), and a brief roadmap of the two or three things you'll cover, in that order. This gives the audience a mental outline to hang the rest of the talk on.
- Signposting as you move through it: explicit verbal markers like "that's the background, now let's get into the actual recommendation" or "second point: ..." help a listener track structure that they can't see the way they could see slide headers or section breaks in a document.
- Body: cover the roadmap items in the order you promised; if you need to deviate, say so explicitly ("I said I'd cover three things, but I want to spend more time on the second one because it's the crux") rather than silently reordering.
- Closing: restate the single most important takeaway in one sentence, ideally the same conclusion you'd have led with in a BLUF-style (bottom-line-up-front) written summary. A talk that just trails off after the last data point leaves the audience to guess what they were supposed to walk away with.
- Time-boxing: decide roughly how much time each section deserves before you start, so the most important section doesn't get squeezed by running long on an earlier one.
Worked example
Opening: "Today I want to cover why our checkout conversion dropped last month, what we found, and what we're proposing to fix it. I'll spend most of the time on the fix, since that's the decision we need from this meeting."
Signposting mid-talk: "That covers the three causes we found. Now, the part that actually needs a decision from you: two options for the fix."
Closing: "So the recommendation is option two: it costs more upfront but avoids the recurring risk we saw with option one. That's the decision I'd like from this meeting."
Each of these three lines exists purely to orient the listener to structure, not to add new content.
Trade-offs and pitfalls
- A talk with too many signposts can feel mechanical; use them at genuine transition points, not after every sentence.
- Promising a roadmap and then not following it (skipping a promised section, or spending disproportionate time on something you said would be brief) breaks the audience's trust in your structure and makes them stop tracking it.
- For a very short talk (under two minutes), an explicit roadmap can eat too much of the available time; at that length, the opening and closing can collapse into a single BLUF-style sentence instead of a separate roadmap plus takeaway.
Describe a situation where you had to tell a stakeholder 'I don't know' about an unexpected result or behavior in your work. How did you handle that moment, what investigation plan did you propose, and how did you maintain trust during the follow-up?
Sample Answer
Direct answer
In the moment, say plainly that you don't yet know, without guessing out loud to fill the silence, immediately pair that admission with a concrete next step so it doesn't sound like a dead end, and afterward protect trust by actually following through on that plan and closing the loop even if the answer takes longer than hoped.
Structured elaboration
- Handling the moment. Resist the pressure to speculate confidently just to have something to say; a wrong guess stated as fact is worse than an honest "I don't know yet," because it can send the stakeholder's own decisions in the wrong direction. Say it plainly: "I don't have a confident answer for why that happened yet."
- Proposing an investigation plan on the spot. Immediately follow the admission with a specific next step and, if possible, a rough timeframe: "I'm going to check X and Y first, and I'll have an update by [a specific time]," rather than an open-ended "I'll look into it." This converts "I don't know" from a dead end into a plan the stakeholder can trust is moving.
- Maintaining trust during follow-up. Actually deliver on the timeframe given, even if the update is "still investigating, here's what I've ruled out so far," rather than the final answer. A stakeholder tolerates not having the answer yet far better than they tolerate silence after being promised an update. If the investigation takes longer, or turns up something uncomfortable, including a mistake, say that plainly too rather than softening it.
Worked example
A stakeholder asks why a report's numbers jumped overnight, and there's no confirmed reason yet. Instead of guessing, "probably a data refresh issue," the response is: "I don't have a confirmed reason yet, I don't want to guess and send you down the wrong path. I'm going to check the two most likely sources, the upstream data feed and a recent code change, and I'll update you by end of day either way." The follow-up happens by end of day as promised, even though the investigation isn't finished: "I've ruled out the code change, still checking the data feed, will have a final answer by tomorrow morning." The next day brings confirmation that it was an upstream data quality issue, along with what's being done about it. Trust holds because every promise about timing was kept, including the intermediate ones.
Trade-offs and pitfalls
Guessing confidently to avoid looking uninformed risks being wrong, which costs more trust than the original "I don't know" would have. Saying "I don't know" with no plan attached reads as unhelpful rather than honest. Promising a timeframe and then going silent when it's not met damages trust more than the original uncertainty did. And over-apologizing or being defensive in the moment can make the stakeholder more anxious rather than reassured that it's being handled.
Describe a move you made into an area next door to the one you knew well. How did you work out what you were missing before it cost you anything, and what did you do about the gaps you found?
Sample Answer
Direct answer
The real risk moving into an area next door to one I know well is assuming it works the same way just because it looks familiar. I deliberately go looking for the differences across more than one category, not only the technical one that's obvious, and I take an immediate, concrete first step against each gap I find rather than noting it and moving on.
Structured elaboration
- Name the trap explicitly. Adjacent areas share enough surface vocabulary and tooling that it's easy to over-transfer confidence from the old area, and the gaps that actually cause damage are often not the technical ones you'd naturally think to check.
- Audit across three categories, not just the obvious one. Technical: does the method or tool I already trust actually behave the same way here. Procedural: how does work actually get reviewed, approved, and shipped in this area, and who has to sign off, since that can differ a lot even when the technical surface looks similar. Regulatory or compliance: is there a rule or constraint here, around data handling, safety, or financial controls for example, that simply didn't exist in my old area.
- Take an immediate first step against each category, not a general resolution to "be careful." For the technical gap: run the approach I'd normally trust on a low-stakes case first and check the result rather than assuming it. For the procedural gap: shadow one real review or approval cycle before running my own. For the regulatory gap: directly ask someone who's been burned by it what assumption from an adjacent area tends to bite people here.
- Prioritize by the cost of being wrong, not by what's easiest to check. The regulatory and procedural gaps are usually less visible and more expensive to discover late than the technical one, so I don't let them wait just because they're less obvious.
Worked example
I moved from testing web applications into testing an embedded device, an area that looked deceptively similar since it was still "testing software." Technically, I assumed my usual approach of testing an isolated component in a fast feedback loop would transfer, so before committing to it I ran it on one low-stakes component first and found the hardware's timing behavior made some of my usual assumptions about test isolation invalid, which I wouldn't have caught by just reading about the differences beforehand. Procedurally, I shadowed one full release cycle before running my own, and discovered signoff required a hardware engineer's review that had no equivalent in my old process, something I'd have missed if I'd started shipping changes the way I used to. On the regulatory side, I asked a colleague who'd been on the team longer what mistake people from a software-only background tended to make, and learned there was a safety-certification constraint on what could even be modified without a formal review, which I would not have thought to look for on my own. Catching all three early meant none of them became an incident; they became a slower first few weeks instead.
Trade-offs and pitfalls
The most common mistake is treating an adjacent move as low-risk simply because it feels familiar, which is exactly what makes the non-technical gaps dangerous: they don't announce themselves the way a technical error does. Checking only the technical axis and assuming procedure and compliance will just work themselves out is the specific version of that mistake. And discovering any of these gaps only after an incident, rather than through a deliberate first step taken early, is the outcome all of this is meant to avoid.
A model starts returning NaN predictions after a library upgrade. Write the bug report you would file, including how you would shrink the problem to a minimal reproduction.
Sample Answer
Direct answer
A model (a program that turns input features, the columns of numbers describing each case, into predictions) is returning NaN (not-a-number, the floating-point value produced by invalid arithmetic) after a library upgrade. My report has to answer four things: what broke, what changed, the smallest way to reproduce it, and how bad it is. The method for shrinking is to freeze the inputs, then repeatedly halve the rows, keeping whichever half still fails, until one row remains, and then drop columns one at a time, keeping each drop that still fails (with only four columns, halving them is not worth the code).
Step 1: confirm and pin
- Check it is deterministic and record the old and new library versions (a comparison of the two environments' package lists shows exactly what changed).
- Freeze one input batch to a file so nothing else varies.
Step 2: shrink with a script
Below, the two predict modes stand in for the old and new library behaviour (old fills missing values with the column mean, new passes them through). In a real report you would replace them with two environments.
import numpy as np
rng = np.random.default_rng(7)
X = rng.normal(size=(512, 4))
X[301, 2] = np.nan # one row has a missing value in feature 2
w = np.array([0.5, -1.0, 0.25, 2.0])
def predict(batch, weights, fill_missing):
batch = batch.copy()
if fill_missing: # old behaviour: replace NaN with the column mean
means = np.nanmean(batch, axis=0)
idx = np.where(np.isnan(batch))
batch[idx] = means[idx[1]]
# batch @ weights = weighted sum per row; 1/(1+exp(-z)) squashes it to a 0-1 probability
return 1 / (1 + np.exp(-(batch @ weights)))
def fails(rows, cols, fill_missing=False):
return bool(np.isnan(predict(X[np.ix_(rows, cols)], w[cols], fill_missing)).any())
ALL = [0, 1, 2, 3]
print("old (fills) has NaN:", fails(list(range(512)), ALL, True))
print("new (no fill) has NaN:", fails(list(range(512)), ALL))
rows = list(range(512)) # shrink rows: keep whichever half still fails
while len(rows) > 1:
half = rows[: len(rows) // 2]
rows = half if fails(half, ALL) else rows[len(rows) // 2 :]
print("minimal failing row index:", rows)
cols = list(ALL) # shrink columns: drop one at a time, keep the drop if it still fails
for c in ALL:
trial = [k for k in cols if k != c]
if trial and fails(rows, trial):
cols = trial
print("columns still needed:", cols)
print("input for that row:", X[rows[0]].tolist()[:4])
print("prediction:", predict(X[np.ix_(rows, ALL)], w, False).tolist())
Output:
old (fills) has NaN: False
new (no fill) has NaN: True
minimal failing row index: [301]
columns still needed: [2]
input for that row: [-1.7415144478985787, -0.8905443058032078, nan, 0.8884531740936087]
prediction: [nan]
Reading it: the old behaviour gives no NaN, the new one does, halving isolates row 301, and dropping columns one at a time shows only feature 2 is needed, the one with the missing value. Halving keeps the half that still fails, which works when one thing triggers the bug. If neither half fails alone, two rows or columns interact: then remove smaller chunks instead of halves (a technique called delta debugging, rarely needed). The failing input is 1 row out of 512, so it affects 1/512 of rows (about 0.2%).
Step 3: shrink further and write it up
Cut to a standalone script that still fails without the real model or data: paste the code above with the data made inline (one row [-1.74, -0.89, NaN, 0.89], the four weights and the predict function), which is about 20 lines, and confirm it prints NaN in a fresh environment. Then check the release notes for the suspect change.
Title: Predictions are NaN for rows with a missing feature after upgrading <library> <old> -> <new>
Severity: Sev-2 (serious but not total). Only rows with a missing value are affected.
Impact: in the sample, 1 of 512 rows (0.2%); downstream ranking drops those users.
Timeline (illustrative): upgrade deployed 03:05 UTC; first NaN in logs 03:12 UTC.
Environment: old and new package lists attached (differences: <library> only).
Minimal repro: attached script, 20 lines, no model file needed.
Sample failing input: [-1.74, -0.89, NaN, 0.89]
Expected: a finite probability (old version imputes the column mean).
Actual: NaN.
Suspected cause (hypothesis, unverified): default handling of missing values changed.
Workaround: impute (fill in the missing value, here with the column mean) before calling predict.
If the trigger is a downstream data pipeline change instead of a library upgrade
Do the same halving on the pipeline's output before and after the change: keep the snapshot timestamps, the first bad output time, and one failing sample record. Report severity and the share of affected records in the same way.
Pitfalls
- Shrinking before freezing the input, so the failure moves.
- Filing a screenshot of the model output instead of the smallest script.
- Presenting the suspected cause as a fact.
Create accessible markup and CSS for an icon-only button (for example, a magnifying-glass search button). Requirements: the button must have an accessible name via aria-label or an offscreen label, a minimum 44×44px touch target, visible focus and hover states, and must not rely solely on title attributes. Provide code snippets and explain choices.
Sample Answer
Direct answer
Use a real <button type="button"> (a native button already has keyboard activation and the button role), put the icon inside as an svg hidden from assistive technology with aria-hidden="true", and give the button its accessible name (the text a screen reader announces for it) either with aria-label="Search" or with a visually hidden <span> of text. Make the clickable box at least 44 by 44 CSS pixels with min-width and min-height, style :hover, :active and :focus-visible states, and never use title as the only label.
The markup and CSS
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Icon-only button</title>
<style>
:root { --ink: #1f2328; --surface: #f1f3f5; --hover: #d0d7de; --ring: #0b57d0; }
body { margin: 16px; background: #fff; }
.icon-btn {
display: inline-flex; align-items: center; justify-content: center;
min-width: 44px; min-height: 44px; /* touch target */
padding: 0; border: 1px solid #8c959f; border-radius: 8px;
background: var(--surface); color: var(--ink); cursor: pointer;
}
.icon-btn svg { width: 24px; height: 24px; fill: none; stroke: currentColor; stroke-width: 2; }
.icon-btn:hover,
.icon-btn:active { background: var(--hover); }
.icon-btn:focus-visible {
outline: 3px solid var(--ring);
outline-offset: 2px; /* gap so the ring is not painted on the button's own colour */
}
/* Text that is read by assistive technology but not drawn. */
.visually-hidden {
position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0;
overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0;
}
</style>
</head>
<body>
<!-- Option 1: aria-label -->
<button type="button" class="icon-btn" id="by-label" aria-label="Search">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<circle cx="10" cy="10" r="6"/><path d="M15 15l6 6"/>
</svg>
</button>
<!-- Option 2: hidden text -->
<button type="button" class="icon-btn" id="by-text">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
<circle cx="10" cy="10" r="6"/><path d="M15 15l6 6"/>
</svg>
<span class="visually-hidden">Search</span>
</button>
</body>
</html>
Choices:
<button type="button">.type="button"stops it submitting a surrounding form. Because it is a native control it is in the Tab order, and the test presses Enter and Space on it and gets a click event for each, with no key-handling script.aria-hidden="true"andfocusable="false"on thesvg. The drawing is decoration; the name comes from the button. The test shows neither button exposes an image role inside it.min-width: 44px; min-height: 44px, notwidthandheight. The 24px icon sits centred in a 44px box (inline-flexwithalign-itemsandjustify-content: center), and the box can still grow if a label or larger text setting is added. WCAG 2.2 criterion 2.5.5 Target Size (Enhanced), level AAA, says "The size of the target for pointer inputs is at least 44 by 44 CSS pixels except when:" (https://www.w3.org/WAI/WCAG22/Understanding/target-size-enhanced.html). The level AA criterion, 2.5.8 Target Size (Minimum), uses "at least 24 by 24 CSS pixels" (https://www.w3.org/WAI/WCAG22/Understanding/target-size-minimum.html), so 44 is the stricter, more comfortable target the requirements ask for.:focus-visible, not:focus. MDN defines it as applying "while an element matches the:focuspseudo-class and the UA (User Agent) determines via heuristics that the focus should be made evident on the element", and notes that "when a button is clicked using a pointing device, the focus is generally not visually indicated" (https://developer.mozilla.org/en-US/docs/Web/CSS/:focus-visible). The ring is a 3px solidoutlinewithoutline-offset: 2px. An outline takes no layout space, so showing it never shifts neighbouring content.- Hover and active share one background change. Hover is a pointer cue only; nothing important is communicated by it.
Why the hidden-text rule is written this way
The .visually-hidden rule keeps the text in the accessibility tree (the browser's list of what assistive technology can announce) while drawing nothing. Each property has one job:
position: absolutetakes the span out of the flow, so it pushes nothing around.width: 1px; height: 1px; margin: -1px; padding: 0; border: 0shrink it to a point that overlaps neighbouring content instead of adding space.overflow: hiddenandclip-path: inset(50%)clip away anything that would still paint inside that point;inset(50%)cuts 50% off every side, which leaves an empty rectangle.white-space: nowrapkeeps the word on one line instead of wrapping inside the 1px box.
display: none and visibility: hidden are not used because both remove the element from the accessibility tree as well as from the screen, so the button would lose its name.
Accessible name: aria-label or hidden text
Both versions are in the listing (#by-label and #by-text). The test (below) asks the browser for a button named "Search" and finds one for each. They differ in one measurable way: with hidden text the word "Search" is real text in the DOM (the DOM property textContent, which returns an element's text, is "Search"), with aria-label the element's textContent is empty and the label lives only in the attribute. Choose aria-label when the label is short and is set from your translated strings in markup; choose hidden text when you want the label to exist as ordinary content (for example, so a test can find it by text). Whichever you pick, the name should describe the action ("Search"), not the picture ("Magnifying glass").
Why title alone is not enough
The same test also builds a button that has only title="Search". All three engines compute the name "Search" for it, so the failure is not an empty name. The problem is that the text is invisible unless a tooltip appears. MDN states that use of the title attribute is "highly problematic for" people using touch-only devices and people navigating with keyboards (https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Global_attributes/title). A sighted keyboard or touch user gets no visible label, so the control should carry a name from aria-label or hidden text. title can be added on top as a mouse tooltip, but not instead.
Proof in three engines
The test loads the exact HTML above in Chromium, Firefox and WebKit and asserts: the box is 44 by 44, the button has the accessible name "Search" (Playwright's getByRole uses the browser's accessibility tree), the svg is not exposed, hover changes the background, a mouse click leaves no outline while Tab shows a solid 3px one, and, by deleting the sizing rule and the :focus-visible rule in turn, that each one is doing the work. It also computes the contrast ratios of the chosen colours with the WCAG relative-luminance formula.
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
const shipped = readFileSync('icon_button.html', 'utf8');
const titleOnly = shipped.replace(' aria-label="Search"', ' title="Search"');
const noSize = shipped.replace('min-width: 44px; min-height: 44px;', '');
const noFocusRule = shipped.replace(/\.icon-btn:focus-visible \{[^}]*\}/, '');
const lum = (hex) => {
const c = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255)
.map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
};
const ratio = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); return ((x + 0.05) / (y + 0.05)).toFixed(2); };
const outline = (el) => { const s = getComputedStyle(el); return `${s.outlineStyle} ${s.outlineWidth}`; };
for (const type of [chromium, firefox, webkit]) {
const browser = await type.launch();
const page = await browser.newPage();
const log = (...a) => console.log(type.name().padEnd(8), ...a);
await page.setContent(shipped);
for (const id of ['by-label', 'by-text']) {
const box = await page.$eval(`#${id}`, (e) => { const r = e.getBoundingClientRect(); return `${r.width}x${r.height}`; });
log(id.padEnd(9), 'size', box, '| role=button name "Search":', await page.locator(`#${id}`).and(page.getByRole('button', { name: 'Search' })).count(), '| svg exposed as image:', await page.locator(`#${id}`).getByRole('img').count(), '| textContent:', JSON.stringify(await page.$eval(`#${id}`, (e) => e.textContent.trim())));
}
await page.setContent(noSize);
log('size rule deleted:', await page.$eval('#by-label', (e) => { const r = e.getBoundingClientRect(); return `${r.width}x${r.height}`; }));
await page.setContent(titleOnly);
log('title only: name', JSON.stringify(await page.locator('#by-label').and(page.getByRole('button', { name: 'Search' })).count() ? 'Search (computed from title)' : 'none'));
await page.setContent(shipped);
const hoverBg = (id) => page.$eval(`#${id}`, (e) => getComputedStyle(e).backgroundColor);
const before = await hoverBg('by-label');
await page.hover('#by-label');
log('hover background', before, '->', await hoverBg('by-label'));
await page.mouse.move(300, 300);
await page.click('#by-label');
log('after mouse click, outline:', await page.$eval('#by-label', outline));
await page.setContent(shipped);
await page.keyboard.press('Tab');
log('after Tab, outline:', await page.$eval('#by-label', outline), '| focused:', await page.evaluate(() => document.activeElement.id));
await page.evaluate(() => { window.hits = []; document.querySelector('#by-label').addEventListener('click', (e) => window.hits.push(e.detail === 0 ? 'keyboard' : 'pointer')); });
await page.keyboard.press('Enter');
await page.keyboard.press('Space');
log('click events from Enter then Space on the focused button:', await page.evaluate(() => window.hits.join(',')));
await page.setContent(noFocusRule);
await page.keyboard.press('Tab');
log('focus rule deleted, outline after Tab:', await page.$eval('#by-label', outline));
await browser.close();
}
console.log('ring #0b57d0 on page #ffffff:', ratio('#0b57d0', '#ffffff'), '| icon #1f2328 on button #f1f3f5:', ratio('#1f2328', '#f1f3f5'), '| button border #8c959f on page #ffffff:', ratio('#8c959f', '#ffffff'));
Output:
chromium by-label size 44x44 | role=button name "Search": 1 | svg exposed as image: 0 | textContent: ""
chromium by-text size 44x44 | role=button name "Search": 1 | svg exposed as image: 0 | textContent: "Search"
chromium size rule deleted: 26x26
chromium title only: name "Search (computed from title)"
chromium hover background rgb(241, 243, 245) -> rgb(208, 215, 222)
chromium after mouse click, outline: none 0px
chromium after Tab, outline: solid 3px | focused: by-label
chromium click events from Enter then Space on the focused button: keyboard,keyboard
chromium focus rule deleted, outline after Tab: auto 1px
firefox by-label size 44x44 | role=button name "Search": 1 | svg exposed as image: 0 | textContent: ""
firefox by-text size 44x44 | role=button name "Search": 1 | svg exposed as image: 0 | textContent: "Search"
firefox size rule deleted: 26x26
firefox title only: name "Search (computed from title)"
firefox hover background rgb(241, 243, 245) -> rgb(208, 215, 222)
firefox after mouse click, outline: none 0px
firefox after Tab, outline: solid 3px | focused: by-label
firefox click events from Enter then Space on the focused button: keyboard,keyboard
firefox focus rule deleted, outline after Tab: auto 1px
webkit by-label size 44x44 | role=button name "Search": 1 | svg exposed as image: 0 | textContent: ""
webkit by-text size 44x44 | role=button name "Search": 1 | svg exposed as image: 0 | textContent: "Search"
webkit size rule deleted: 26x26
webkit title only: name "Search (computed from title)"
webkit hover background rgb(241, 243, 245) -> rgb(208, 215, 222)
webkit after mouse click, outline: none 0px
webkit after Tab, outline: solid 3px | focused: by-label
webkit click events from Enter then Space on the focused button: keyboard,keyboard
webkit focus rule deleted, outline after Tab: auto 5px
ring #0b57d0 on page #ffffff: 6.39 | icon #1f2328 on button #f1f3f5: 14.20 | button border #8c959f on page #ffffff: 3.04
Reading it: with the sizing rule deleted the button measures 26 by 26 (24px icon plus a 1px border each side), so the 44px rule is what creates the target. With the :focus-visible rule deleted, Tab shows only the browser's default auto outline (1px in Chromium and Firefox, 5px in WebKit), so the 3px solid ring is ours. After a mouse click the outline is none in all three engines, because :focus-visible does not match, while Tab shows the ring. WCAG (the Web Content Accessibility Guidelines) grades each criterion at level A, AA or AAA; AA is the level most policies and contracts ask for, and AAA is stricter. The contrast ratio is computed from relative luminance, a number from 0 (black) to 1 (white) that weighs red, green and blue by how bright the eye finds each (green counts most). Each 0-255 channel is divided by 255, linearised to undo the screen's gamma curve (the two constants in lum do that), then combined as 0.2126 R + 0.7152 G + 0.0722 B. The ratio is (lighter + 0.05) / (darker + 0.05). For the ring #0b57d0 the channels 0.0431, 0.3412 and 0.8157 linearise to 0.0033, 0.0953 and 0.6308, giving a luminance of 0.1144; white is 1, so the ratio is 1.05 / 0.1644 = 6.39. The icon #1f2328 has luminance 0.0165 and the button face #f1f3f5 has 0.8939, so (0.8939 + 0.05) / (0.0165 + 0.05) = 14.20. The ring's 6.39:1 is above the 3:1 that WCAG 1.4.11 Non-text Contrast (level AA) requires for "visual information required to identify user interface components and states" (https://www.w3.org/WAI/WCAG22/Understanding/non-text-contrast.html). The icon is 14.20:1 on the button face and the button border (luminance 0.2957) is 3.04:1 against the page. Those ratios are for this palette on a white page; on a dark background recompute them, because the ring sits in the 2px gap and is judged against what is next to it. WebKit in Playwright is not Safari on iOS.
Pitfalls
- A
divorspanwith a click handler has none of this for free: no focus, no key handling, no role. - Do not remove the outline with
outline: noneand leave nothing in its place. - Icon-only buttons crowd toolbars: two 44px targets with no gap are still two 44px targets, but add spacing so a thumb does not hit the neighbour.
Running the code
npm init -y && npm pkg set type=module
npm i playwright@1.48.2
npx playwright install chromium firefox webkit
# save the HTML listing as icon_button.html next to icon_button.mjs
node icon_button.mjs
Run in the mcr.microsoft.com/playwright:v1.48.2-jammy image (browsers preinstalled; skip the install line there).
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.
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