Frontend Developer Mid-Level Interview Preparation Guide (FAANG Standards)
This guide is based on general FAANG interview practices and may not reflect specific company procedures.
FAANG companies typically conduct 6-8 interview rounds for mid-level frontend developers, progressing from recruiter screening through multiple technical evaluations (coding, UI implementation, and system design), behavioral assessment, and leadership conversations. Mid-level candidates are expected to demonstrate strong technical proficiency, ability to own projects end-to-end, mentorship of junior developers, and alignment with company culture. The interview process emphasizes problem-solving approach, communication, code quality, and growth trajectory.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with a technical recruiter to assess general fit, background, career trajectory, and alignment with the role and company. This is a preliminary filter to ensure you meet minimum requirements and are genuinely interested. Expect questions about your current role, motivation for the move, location/visa requirements, and timeline.
Tips & Advice
Be clear and concise about your motivation for applying. Have a strong 2-minute summary of your frontend development experience ready. Ask thoughtful questions about the role, team structure, and technology stack. Emphasize your track record with performance, user experience, or specific technical achievements. Be honest about timeline and constraints to avoid mismatches later.
Focus Topics
Technical Stack Familiarity
Discuss your hands-on experience with relevant technologies: modern JavaScript frameworks (React, Vue, Angular), CSS, responsive design, state management, API integration, and performance optimization tools.
Practice Interview
Study Questions
Motivation and Company Alignment
Articulate why you're interested in this specific role and company. Connect your interests (e.g., working on high-scale systems, specific technology stack, company mission) to genuine alignment rather than generic reasons.
Practice Interview
Study Questions
Career Background and Progression
Clearly articulate your 2-5 years of frontend development experience, key projects you've led or contributed to, and progression from junior to mid-level responsibilities. Discuss growth in technical depth and scope of ownership.
Practice Interview
Study Questions
Technical Phone Screen (JavaScript Fundamentals)
What to Expect
First technical round conducted via video call, focusing on core JavaScript knowledge and basic problem-solving. Expect 1-2 coding problems of medium difficulty that test understanding of JavaScript fundamentals, data structures, and algorithms. May include live coding on a shared platform (CodePen, CoderPad, or similar). This round assesses whether you have strong foundational JavaScript knowledge required for more advanced rounds.
Tips & Advice
Think aloud throughout the problem-solving process. Start by clarifying the problem and edge cases before writing code. Write clean, readable code with meaningful variable names. Test your solution mentally with examples. If stuck, communicate your thinking and ask for hints rather than sitting silently. Optimize after getting a working solution if time permits. Practice on LeetCode medium-level problems and JavaScript-specific challenges (implementing Array methods, Promise polyfills, etc.).
Focus Topics
DOM Manipulation and Browser APIs
Understanding of DOM structure, methods for selecting and manipulating elements (querySelector, getElementById, etc.), event handling, and browser APIs relevant to frontend development.
Practice Interview
Study Questions
Problem Solving and Algorithm Thinking
Ability to break down problems into smaller steps, consider edge cases, and optimize solutions. Understand basic algorithmic concepts like sorting, searching, and time complexity analysis.
Practice Interview
Study Questions
Array and Object Manipulation
Proficiency with array methods (map, filter, reduce, sort, find, etc.), object manipulation techniques, and common data transformation patterns. Understand time and space complexity of these operations.
Practice Interview
Study Questions
JavaScript ES6+ Fundamentals
Master modern JavaScript syntax and features including arrow functions, destructuring, spread operator, template literals, let/const scoping, classes, async/await, Promises, and modules. Understand the event loop, closure, prototypal inheritance, and the this keyword in different contexts.
Practice Interview
Study Questions
Technical On-site Round 1 (Advanced JavaScript & Framework Expertise)
What to Expect
Second technical round (typically on-site or extended video interview) focusing on deeper JavaScript knowledge and framework expertise. Expect 1-2 coding problems that may involve implementing utilities, understanding framework concepts, or solving real-world frontend challenges. Questions may explore state management patterns, component lifecycle, hooks (if React), reactivity (if Vue), or dependency injection (if Angular).
Tips & Advice
Before the interview, review your most recent framework project in detail. Be prepared to discuss architectural decisions and trade-offs. Practice implementing utility functions commonly found in production (debounce, throttle, memoization, etc.). Understand async patterns deeply—how Promises chain, error handling in async/await, and race conditions. Prepare to explain how your chosen framework handles reactivity, component updates, and performance. Code with production quality in mind: error handling, edge cases, maintainability.
Focus Topics
Closures and Scope in Practical Context
Deep understanding of JavaScript closures, lexical scope, and how they apply to real patterns like event handlers, callbacks, custom hooks, and module patterns. Ability to identify and fix closure-related bugs.
Practice Interview
Study Questions
State Management Patterns
Understanding of different state management approaches: local component state, lifting state up, Context API, Redux/Vuex patterns, or other state libraries. Knowledge of when to use each approach and trade-offs between complexity and scalability.
Practice Interview
Study Questions
Performance Optimization Techniques
Practical techniques for optimizing frontend performance: memoization, React.memo, useMemo, useCallback hooks, code splitting, lazy loading, bundle optimization, and understanding rendering performance issues. Knowledge of tools like Chrome DevTools and Lighthouse.
Practice Interview
Study Questions
Asynchronous Programming and Promises
Complete mastery of Promises, async/await, error handling, race conditions, and common patterns like Promise.all(), Promise.race(), Promise.allSettled(). Understanding of callback patterns, event-driven architecture, and how async operations integrate with component lifecycle.
Practice Interview
Study Questions
React Fundamentals (or Vue/Angular depending on expertise)
Deep understanding of component architecture, hooks (useState, useEffect, useContext, useReducer, custom hooks), lifecycle methods, rendering optimization, and component composition patterns. Knowledge of controlled vs uncontrolled components, prop drilling vs context API, and when to use each pattern.
Practice Interview
Study Questions
Technical On-site Round 2 (UI Component Implementation & Practical Coding)
What to Expect
Third technical round focused on practical UI component implementation. You'll be asked to build a UI component or small application feature from scratch using HTML, CSS, and JavaScript (typically in your chosen framework). Examples include building an autocomplete dropdown, carousel, pagination component, form with validation, or similar. This round tests your ability to translate requirements into working code, handle edge cases, and produce production-quality UI.
Tips & Advice
Read the requirements carefully and ask clarifying questions before starting. Plan your approach: break the component into smaller pieces, think through state and event handling, then implement. Write semantic HTML first, then add styling and interactivity. Consider accessibility from the start (ARIA labels, keyboard navigation, screen reader compatibility). Test your implementation mentally or in the browser with edge cases. Write clean CSS—organize styles logically, avoid inline styles, consider responsiveness. For the JavaScript, handle events properly, manage component state clearly, and write reusable code. Leave time to refactor or optimize if the basic implementation is working.
Focus Topics
Cross-browser Compatibility and Testing
Knowledge of common browser compatibility issues, progressive enhancement, polyfills when needed, and testing across different browsers and devices. Understanding of how to use browser DevTools to debug issues.
Practice Interview
Study Questions
Component State Management and Props
Managing component state effectively, understanding when to use local state vs lifted state, prop passing, handling prop changes, and avoiding common pitfalls like stale closures or missing dependency arrays.
Practice Interview
Study Questions
Form Handling and Validation
Building forms with proper validation, error messaging, disabled states, and user feedback. Handling form submission, preventing double-submission, and integrating with backend APIs. Understanding controlled vs uncontrolled components in React context.
Practice Interview
Study Questions
Event Handling and User Interaction
Proper implementation of click handlers, form submissions, keyboard events, touch events, and event delegation. Understanding of event bubbling, event target, and how to handle events efficiently.
Practice Interview
Study Questions
Semantic HTML and Accessibility
Writing semantic, accessible HTML using appropriate elements (form, button, nav, article, etc.), ARIA attributes where needed, keyboard navigation support, screen reader compatibility, and inclusive design principles. Understanding of WCAG guidelines at a practical level.
Practice Interview
Study Questions
Responsive CSS and Layout
Mastery of CSS Grid, Flexbox, media queries, and responsive design principles. Understanding of CSS specificity, cascading, box model, and how to write maintainable CSS. Knowledge of CSS-in-JS approaches if using them. Ability to style components to match design specifications.
Practice Interview
Study Questions
System Design Round (Frontend Architecture & Scalability)
What to Expect
Focused on architectural thinking, scalability, and design patterns at the frontend level. You may be asked to design a system for a feature (e.g., designing a real-time notification system UI, building an infinite scroll implementation, architecting a complex form with multiple steps, or designing state management for a large application). This round tests your ability to think about scalability, performance, maintainability, and trade-offs. Unlike backend system design, frontend system design emphasizes user experience, performance, state management, and component architecture.
Tips & Advice
Start by understanding the requirements and constraints. Ask clarifying questions about scale, user expectations, performance requirements, and device support. Sketch your approach on a whiteboard or document—show component structure, data flow, state management approach. Discuss trade-offs: simplicity vs scalability, client-side vs server-side rendering, caching strategies, performance optimization techniques. Consider edge cases like network failures, loading states, error handling, and accessibility. Be prepared to dive deeper into specific areas (e.g., state management library selection, performance monitoring, testing strategy). For mid-level, demonstrate that you've thought about scaling beyond a simple solution.
Focus Topics
Handling Real-time Data and Server Communication
Strategies for managing real-time updates (WebSockets, Server-Sent Events, polling), synchronizing state with backend, handling offline scenarios, conflict resolution, and optimistic UI updates. Understanding of caching and data consistency.
Practice Interview
Study Questions
Testing Strategy and Error Handling
Planning a testing strategy for frontend systems: unit tests, integration tests, E2E tests, and the testing pyramid. Error boundaries, error recovery, graceful degradation, and user feedback mechanisms.
Practice Interview
Study Questions
Frontend Performance and Optimization
Strategies for optimizing performance: code splitting, lazy loading, caching (browser cache, CDN, memoization), bundling optimization, critical rendering path optimization, and monitoring tools. Understanding of Core Web Vitals and real user monitoring.
Practice Interview
Study Questions
State Management Strategy
Choosing appropriate state management solutions for different scenarios: local state for isolated components, lifted state for multiple components, Context API for shared state, or external libraries like Redux/Vuex for complex applications. Understanding when each approach is suitable.
Practice Interview
Study Questions
Component Architecture and Design Patterns
Designing scalable component hierarchies, understanding container vs presentational components, composition over inheritance, render props, higher-order components, or hooks patterns. Ability to break down complex UIs into manageable, reusable components.
Practice Interview
Study Questions
Behavioral Round (Project Ownership & Collaboration)
What to Expect
Focused on your past experiences, leadership qualities, teamwork, project ownership, and ability to mentor junior developers. Expect behavioral questions using the STAR method (Situation, Task, Action, Result). Questions typically explore: a challenging technical problem you solved, a time you took ownership of a project, conflict with a team member, mentoring a junior developer, learning something new, and handling ambiguous requirements. For mid-level, emphasize examples showing you own projects end-to-end, collaborate effectively, and develop others.
Tips & Advice
Prepare 5-7 concrete stories from your actual experience that demonstrate different competencies (ownership, learning, collaboration, problem-solving, mentorship). Use the STAR method: clearly set up the situation, explain your specific task/responsibility, describe the action you took (focus on 'I' not 'we'), and quantify the result. Be specific with metrics where possible (e.g., 'improved page load time by 40%', 'mentored 2 junior developers'). Practice telling these stories concisely—each should take 2-3 minutes. Show self-awareness: acknowledge mistakes honestly and explain what you learned. For mid-level, show examples of ownership (leading features, making technical decisions), not just individual contribution.
Focus Topics
Handling Ambiguity and Taking Initiative
Examples of working on projects with unclear requirements, how you clarified ambiguity, took initiative to propose solutions, and drove clarity in ambiguous situations.
Practice Interview
Study Questions
Collaboration and Cross-functional Teamwork
Examples of working closely with designers, backend engineers, product managers, or other teams. How you communicate, handle disagreements professionally, and find solutions that balance different perspectives.
Practice Interview
Study Questions
Technical Problem-Solving and Learning Agility
Examples of difficult technical problems you solved, your approach to understanding complex systems, how you troubleshoot issues, and examples of learning new technologies or frameworks on the job.
Practice Interview
Study Questions
Mentorship and Developing Others
Specific examples of mentoring junior developers: code reviews you led, teaching moments, helping someone grow technically, or onboarding them to projects. Show how you provide feedback, support growth, and improve code quality.
Practice Interview
Study Questions
Project Ownership and End-to-End Delivery
Examples of projects where you took ownership from design through deployment, made technical decisions, managed scope, handled setbacks, and delivered results. Demonstrate ability to see projects through completion and take accountability.
Practice Interview
Study Questions
Hiring Manager Round
What to Expect
Final round with the hiring manager or senior team member to assess overall fit, career aspirations, growth mindset, and alignment with team culture. This round is more conversational and less about technical testing. Expect questions about your career goals, what kind of problems interest you, how you prefer to work, your approach to code quality, and your understanding of the role's responsibilities. The hiring manager is assessing whether you'll be a good long-term fit and how you'll grow in the role.
Tips & Advice
Research the team, products, and impact they're working on. Prepare thoughtful questions about the role, team dynamics, growth opportunities, and company culture. Be authentic about your career interests and growth areas—this is not a time to oversell or pretend to be someone you're not. Show curiosity about the work and genuine enthusiasm. Listen carefully to the manager's description of the role and respond thoughtfully. Ask about the biggest technical challenges the team faces, the team's culture and working style, and opportunities for growth. Be honest about your strengths and areas for development.
Focus Topics
Understanding of Role Responsibilities
Demonstrate that you understand what mid-level frontend developers do at FAANG: own features end-to-end, mentor juniors, contribute to architectural decisions, and drive code quality. Show realistic expectations about the role.
Practice Interview
Study Questions
Cultural Fit and Values Alignment
Understanding and genuine alignment with company values (e.g., Amazon's Leadership Principles, Meta's values, Google's philosophy). Examples from your experience that demonstrate these values.
Practice Interview
Study Questions
Code Quality and Engineering Excellence
Your philosophy on code quality, testing, refactoring, and continuous improvement. How you approach technical debt, code reviews, and maintaining high standards while shipping features.
Practice Interview
Study Questions
Career Goals and Growth Mindset
Clear articulation of your career trajectory, where you want to go (senior IC, tech lead, architect), what skills you're developing, and how this role fits into your growth plan. Show commitment to continuous learning and improving.
Practice Interview
Study Questions
Frequently Asked Frontend Developer Interview Questions
You are implementing a date field with a calendar popup for a booking form. What edge cases do you plan for before calling it done, and how do you handle each: users in different locales, typed rather than picked dates, invalid or out-of-range dates, keyboard and touch use, and a calendar that must render many dates?
Sample Answer
Direct answer
Before calling a date field done I would settle five things. (1) Store and send the date as a plain calendar date in ISO yyyy-mm-dd form, and format it for display with Intl.DateTimeFormat, so locale only changes what the user sees. (2) Default to the native <input type="date"> with min and max, because it gives locale order, keyboard entry and the platform's touch picker for free, and build a custom calendar only when the booking needs something the native picker cannot do (blocked days, a price per night, a two-date range). (3) Treat every typed value as untrusted: reject impossible dates such as 30 February, treat a year typed halfway (such as 0020) as invalid, and check the range yourself as well as through the browser. (4) Make the calendar a keyboard-operable grid with focus returned to the trigger. (5) Render only the visible month and fetch availability per month.
Lead with (1) and (3): they decide whether the stored data is correct, while (4) and (5) are about how the control feels and scales. Terms used here: ISO yyyy-mm-dd is the international year-month-day format (ISO 8601), Intl.DateTimeFormat is the built-in browser and Node API that formats dates for a locale, and UTC is the zero-offset reference time zone.
Locales: values are ISO, display is local
<input type="date"> always exposes .value as yyyy-mm-dd, whatever order the user sees (MDN). Playwright 1.48.2 with the en-US and de-DE locales in Chromium, Firefox and WebKit all returned 2026-05-09 for the same field, even though the visible order differs. So the submitted value is never locale-dependent; only a custom text field has to know the order. The code below reads the order from Intl.DateTimeFormat(...).formatToParts rather than hard-coding it, because 03/04/2026 is 4 March in the US and 3 April in Great Britain.
The classic time zone bug is new Date('2026-03-01'): a date-only ISO string is parsed as midnight UTC, so a user west of UTC sees the day before. Traced for Los Angeles in early March (8 hours behind UTC): midnight UTC on 1 March is 4 pm on 28 February on a Los Angeles clock, so toLocaleDateString prints 2/28/2026, which is the second line of the run below (the first prints the time zone). The code stores {y, m, d}, never a Date, and formats with timeZone: 'UTC' on a UTC-built Date, which cannot shift. The week also starts on a different day by locale: Intl.Locale#getWeekInfo().firstDay (1 is Monday, 7 is Sunday) says which, with an older weekInfo getter in some engines. (formatToParts returns the formatted date as a list of {type, value} pieces such as {type: 'month', value: '03'}, which is how the code learns the field order.)
Typed, invalid and out-of-range dates
| Case | What to do |
|---|---|
| Impossible date (30 February, 31 April) | Re-build the date and compare the parts. new Date('2026-02-30') does not reject it in V8 (the JavaScript engine of Chrome and Node; it is a valid object, rolled into March), so a "did it parse" test passes wrongly. |
| Half-typed date | In the native control value is '' until the month, day and at least one digit of the year are filled, so valueMissing stays true until then. After that value is already a complete date with a tiny year. In Playwright 1.48.2 (10 runs per browser, identical every run), typing the keys 0, 5, 0, 9, 2, 0, 2, 6 into an en-US required date field in Chromium and Firefox gave value '' after each of the first four keys, 0002-05-09 after the fifth, 0020-05-09 after the sixth, 0202-05-09 after the seventh and 2026-05-09 after the eighth, with validity.valid true from the fifth key on. badInput was true after the second, third and fourth keys (a segment in progress) and false once a value existed. In the WebKit build the keyboard did not fill the date segments at all (value stayed ''), so none of this could be reproduced there. So a year typed halfway is a valid-looking value: set min, so that 0020-05-09 fails with rangeUnderflow, and check the year yourself. Do not rely on badInput alone: badInput and valueMissing can both be true at once, and support for the half-typed state varies by browser, so check value === '' and show the message yourself. Show "Enter a full date" on blur or submit, not while typing. |
Before min / after max | Set min/max on the input (MDN: the picker disables out-of-range days, and a value before min sets validity.rangeUnderflow, which Chromium, Firefox and WebKit all reported in a Playwright run), and also compare in code, because a custom text field has no constraint validation and the server must re-check anyway. |
| Two-digit years, other separators | Accept /, . and - as separators; reject 4/3/26 with a format message rather than guessing the century. |
| Unavailable days (fully booked) | Mark the cell aria-disabled="true" and keep it focusable so arrow-key movement is not interrupted; say why in the cell's label ("14 March, fully booked"). |
Keyboard and touch
For a custom picker follow the WAI-ARIA Authoring Practices date picker dialog: the trigger opens a role="dialog" containing a role="grid" with a roving tabindex (exactly one cell is in the Tab order). In plain terms: role="dialog" marks a layer over the page that keeps focus inside it; role="grid" marks a two-dimensional set of cells moved through with arrow keys; roving tabindex means the one cell that currently has focus gets tabindex="0" and every other cell tabindex="-1", and the script swaps them as focus moves, so Tab passes through the whole grid in one stop; and aria-live="polite" makes a screen reader announce changed text when it next pauses. A minimal skeleton (WAI-ARIA Authoring Practices date picker dialog pattern; exactly 1 of the 3 cells, the one with tabindex="0", is in the Tab order):
<button aria-haspopup="dialog" aria-expanded="true">Choose date</button>
<div role="dialog" aria-modal="true" aria-labelledby="month">
<h2 id="month" aria-live="polite">March 2026</h2>
<table role="grid" aria-labelledby="month">
<tr>
<td role="gridcell" tabindex="-1">28</td>
<td role="gridcell" tabindex="0" aria-selected="true">1</td>
<td role="gridcell" tabindex="-1" aria-disabled="true">2</td>
</tr>
</table>
</div>
Arrow keys move by day or week, Home and End go to the start or end of the week, Page Up and Page Down change month (Shift for year), Enter or Space selects and closes, Escape closes and returns focus to the trigger, and the month heading is aria-live="polite" so the change is announced. The text input stays usable beside the button, which is what makes typing a first-class path rather than a fallback. On touch, prefer the native picker (type="date") because the operating system renders its own wheel or calendar; a custom grid needs large tap targets and must not rely on hover.
A calendar that must render many dates
A month never needs more than 42 cells (6 weeks of 7), so render the visible month only, not the whole booking window. Fetch availability per month and prefetch the next one. The last lines of the run below show the cell count depends on the locale's first weekday: February 2026 is exactly 4 weeks with a Sunday start and 5 with a Monday start. The arithmetic in monthGrid: 1 February 2026 is a Sunday (getUTCDay 0) and the month has 28 days. With a Sunday start (en-US) the leading blanks are (0 - 0 + 7) % 7 = 0, so cells = ceil(28 / 7) x 7 = 28, 4 weeks. With a Monday start (en-GB) the leading blanks are (0 - 1 + 7) % 7 = 6, so cells = ceil((6 + 28) / 7) x 7 = 5 x 7 = 35, 5 weeks. If a design shows 12 months at once, that is up to 12 x 42 = 504 cells; at that point render months lazily as they scroll into view (virtualisation) rather than building all of them.
Code and run
// Calendar dates are {y, m, d} values, never Date objects, so no time zone can shift them.
export function isValidYmd(y, m, d) {
const t = new Date(Date.UTC(y, m - 1, d));
return y >= 1000 && t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d;
}
export function toIso({ y, m, d }) {
return `${String(y).padStart(4, '0')}-${String(m).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
}
// Strict yyyy-mm-dd, the format <input type="date"> uses for .value in every locale.
export function parseIso(s) {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
if (!m) return null;
const [y, mo, d] = [+m[1], +m[2], +m[3]];
return isValidYmd(y, mo, d) ? { y, m: mo, d } : null;
}
// Field order for a locale, read from Intl instead of hard-coded: ['month','day','year'] for en-US.
export function fieldOrder(locale) {
return new Intl.DateTimeFormat(locale, { year: 'numeric', month: '2-digit', day: '2-digit' })
.formatToParts(new Date(Date.UTC(2026, 10, 25)))
.filter((p) => ['day', 'month', 'year'].includes(p.type))
.map((p) => p.type);
}
// Typed text such as "05/09/2026" or "9.5.2026", interpreted in the locale's field order.
export function parseTyped(text, locale) {
const parts = text.trim().split(/[^0-9]+/).filter(Boolean);
if (parts.length !== 3 || !/^\d+$/.test(parts.join(''))) return { error: 'format' };
const v = {};
fieldOrder(locale).forEach((k, i) => (v[k] = +parts[i]));
if (String(parts[fieldOrder(locale).indexOf('year')]).length !== 4) return { error: 'format' };
return isValidYmd(v.year, v.month, v.day) ? { date: { y: v.year, m: v.month, d: v.day } } : { error: 'impossible' };
}
export function checkRange(date, minIso, maxIso) {
const iso = toIso(date);
if (minIso && iso < minIso) return 'before-min';
if (maxIso && iso > maxIso) return 'after-max';
return null; // ISO strings of equal length sort chronologically
}
export function display(date, locale) {
return new Intl.DateTimeFormat(locale, { dateStyle: 'long', timeZone: 'UTC' })
.format(new Date(Date.UTC(date.y, date.m - 1, date.d)));
}
// Only the visible month is rendered: leading blanks + days, padded to whole weeks.
export function monthGrid(y, m, locale) {
const loc = new Intl.Locale(locale);
const info = loc.getWeekInfo ? loc.getWeekInfo() : loc.weekInfo; // older engines expose a weekInfo getter
const first = info.firstDay % 7; // Intl: 1=Mon..7=Sun, getUTCDay: 0=Sun
const days = new Date(Date.UTC(y, m, 0)).getUTCDate();
const lead = (new Date(Date.UTC(y, m - 1, 1)).getUTCDay() - first + 7) % 7;
const cells = Math.ceil((lead + days) / 7) * 7;
return { lead, days, cells, weeks: cells / 7 };
}
import assert from 'node:assert/strict';
import { parseIso, parseTyped, checkRange, display, fieldOrder, monthGrid, toIso } from './date-utils.mjs';
console.log('TZ =', process.env.TZ);
// 1. The classic bug: new Date('2026-03-01') is UTC midnight, so west of UTC it prints the previous day.
console.log('new Date("2026-03-01").toLocaleDateString("en-US"):', new Date('2026-03-01').toLocaleDateString('en-US'));
console.log('display({2026,3,1}, "en-US"):', display({ y: 2026, m: 3, d: 1 }, 'en-US'));
assert.equal(display({ y: 2026, m: 3, d: 1 }, 'en-US'), 'March 1, 2026');
// 2. Impossible and incomplete dates
console.log('Date("2026-02-30") valid?', !Number.isNaN(new Date('2026-02-30').getTime()), '| parseIso("2026-02-30"):', parseIso('2026-02-30'));
assert.equal(parseIso('2026-02-30'), null);
assert.deepEqual(parseIso('2028-02-29'), { y: 2028, m: 2, d: 29 });
assert.equal(parseIso('2026-02-29'), null);
// 3. The same keystrokes mean different dates per locale
console.log(fieldOrder('en-US'), fieldOrder('de-DE'), fieldOrder('ja-JP'));
console.log('"03/04/2026" en-US ->', toIso(parseTyped('03/04/2026', 'en-US').date), '| en-GB ->', toIso(parseTyped('03/04/2026', 'en-GB').date));
console.log('"31.04.2026" de-DE ->', JSON.stringify(parseTyped('31.04.2026', 'de-DE')));
console.log('"4/3/26" en-US ->', JSON.stringify(parseTyped('4/3/26', 'en-US')));
assert.equal(toIso(parseTyped('03/04/2026', 'en-US').date), '2026-03-04');
assert.equal(toIso(parseTyped('03/04/2026', 'en-GB').date), '2026-04-03');
assert.equal(parseTyped('31.04.2026', 'de-DE').error, 'impossible');
// 4. Range
console.log(checkRange({ y: 2026, m: 2, d: 15 }, '2026-03-01', '2026-12-31'), checkRange({ y: 2026, m: 5, d: 9 }, '2026-03-01', '2026-12-31'));
assert.equal(checkRange({ y: 2027, m: 1, d: 1 }, '2026-03-01', '2026-12-31'), 'after-max');
// 5. Calendar size: cells rendered per month depends on the locale's first weekday
for (const loc of ['en-US', 'en-GB']) {
const rows = [];
for (let m = 1; m <= 12; m++) rows.push(monthGrid(2026, m, loc).weeks);
console.log(loc, 'weeks per month in 2026:', rows.join(','), '| max cells:', Math.max(...rows) * 7);
}
console.log('Feb 2026 en-US', monthGrid(2026, 2, 'en-US'), 'en-GB', monthGrid(2026, 2, 'en-GB'));
console.log('ALL ASSERTIONS PASSED');
Saved as date-utils.mjs and demo.mjs in one folder and run with env TZ=America/Los_Angeles node demo.mjs in a node:22 container (Node 22.23.3), it prints:
TZ = America/Los_Angeles
new Date("2026-03-01").toLocaleDateString("en-US"): 2/28/2026
display({2026,3,1}, "en-US"): March 1, 2026
Date("2026-02-30") valid? true | parseIso("2026-02-30"): null
[ 'month', 'day', 'year' ] [ 'day', 'month', 'year' ] [ 'year', 'month', 'day' ]
"03/04/2026" en-US -> 2026-03-04 | en-GB -> 2026-04-03
"31.04.2026" de-DE -> {"error":"impossible"}
"4/3/26" en-US -> {"error":"format"}
before-min null
en-US weeks per month in 2026: 5,4,5,5,6,5,5,6,5,5,5,5 | max cells: 42
en-GB weeks per month in 2026: 5,5,6,5,5,5,5,6,5,5,6,5 | max cells: 42
Feb 2026 en-US { lead: 0, days: 28, cells: 28, weeks: 4 } en-GB { lead: 6, days: 28, cells: 35, weeks: 5 }
ALL ASSERTIONS PASSED
With TZ=Pacific/Auckland (east of UTC) the naive line prints 3/1/2026 and the others are unchanged, so the bug only appears for some users, which is why it survives code review done in one time zone.
Trade-offs
- Native versus custom: native wins on accessibility, locale and mobile effort; custom wins when the booking logic (blocked dates, range highlighting, prices) must be visible in the grid. Commit to native unless that requirement exists.
- Validate when: on blur and on submit, not on each keystroke, since a date is invalid until the last digit is typed.
- Pitfall: treating the server as optional. A client check protects the user's time; the server re-validates the range, the availability and the format, because anything can be posted.
Explain the WebSocket opening handshake and how it differs from a typical HTTP request/response flow. Compare WebSocket with HTTP/2 server push and SSE in terms of compatibility with HTTP proxies, TLS termination, connection upgrade requirements, and failure modes when intermediaries interfere. Describe practical mitigations for proxy or firewall incompatibilities.
Sample Answer
Direct answer
A WebSocket starts life as an ordinary HTTP/1.1 GET with an Upgrade: websocket header; if the server agrees it answers 101 Switching Protocols, and from then on the same TCP connection stops being HTTP and carries WebSocket frames in both directions for as long as it lives. A normal HTTP exchange is one request, one response, done. That upgrade is exactly what trips up intermediaries: a proxy that does not understand it strips the header, times out the "idle" connection, or buffers it. SSE avoids the problem by being a plain long HTTP response, and HTTP/2 server push is not an alternative for messaging at all. The main mitigations are always use wss:// on port 443, send heartbeats shorter than any idle timeout, configure your own proxies explicitly, and keep an SSE or long-polling fallback.
The handshake step by step
Client request:
GET /chat HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com
Server response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Keyis 16 random bytes, base64-encoded. It is not a security credential; it proves the server really speaks WebSocket (and did not just echo a cached HTTP response).- The server computes
Sec-WebSocket-Accept= base64(SHA-1(key + the fixed GUID258EAFA5-E914-47DA-95CA-C5AB0DC85B11)). This runnable Python reproduces the value above, which is the example from RFC 6455, the WebSocket specification:
import base64, hashlib
key = "dGhlIHNhbXBsZSBub25jZQ=="
guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
print(base64.b64encode(hashlib.sha1((key + guid).encode()).digest()).decode())
s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Originlets the server reject pages from other sites (browsers send it; check it, because cookies are sent automatically on the handshake).- After the 101, both sides exchange frames: small headers plus payload, with ping/pong control frames and a close handshake. Client-to-server frames are masked with a random 4-byte key, which exists to stop a malicious page from making the bytes on the wire look like a valid HTTP request to a confused cache: without masking, JavaScript on an attacker's page could choose a payload that, byte for byte, reads as a second HTTP request smuggled inside the stream, and a shared cache sitting in front of the server could mistake that smuggled request's response for real traffic and serve the attacker's chosen content to other users.
How it differs from a normal HTTP request/response: normal HTTP is request-driven and finished after each response; the connection may be reused but every exchange is independent and visible to intermediaries as requests. After a WebSocket upgrade there are no more requests, no status codes, no per-message headers; the server can send at any moment, and a proxy sees one very long opaque exchange.
Compatibility comparison
| Concern | WebSocket | SSE | HTTP/2 server push |
|---|---|---|---|
| HTTP proxies | Upgrade and Connection are hop-by-hop headers (meant only for the very next proxy, not copied through automatically the way most headers are, so passing them on is opt-in): every proxy must deliberately forward them. Transparent proxies (proxies a client never configured and does not know exist, inserted into the path by a network operator) on plain ws:// often strip them or break the stream | Plain HTTP GET with a streamed response; passes through nearly all proxies, but buffering proxies delay events until the response "finishes" (never) | Only works hop by hop if every intermediary speaks HTTP/2 end to end; most CDNs do not forward push |
| TLS termination | TLS termination is the point in the network where encrypted traffic is decrypted back to plain bytes; only the box that terminates TLS can read or rewrite the handshake, everything downstream of it just sees plaintext. With wss:// a plain proxy sees only an encrypted tunnel it cannot read (opened with the HTTP CONNECT method, which asks the proxy to stop parsing and just relay raw bytes to the destination) and cannot interfere, unless it deliberately intercepts TLS (terminates it itself with its own certificate so it can read and modify the decrypted traffic, a common corporate-network setup). The terminating load balancer must support upgrades and long idle timeouts | Terminates like any HTTPS request; the load balancer needs streaming (no buffering) and a long idle timeout | Push is sent from the server that terminated TLS; anything behind that is invisible to the browser |
| Upgrade requirement | Yes (HTTP/1.1 Upgrade, or RFC 8441 extended CONNECT on HTTP/2, which fewer intermediaries support) | None | None, but only in response to a client request |
| Failure modes when intermediaries interfere | Handshake rejected (400, 403), upgrade silently stripped (response is a normal 200), connection accepted then frames dropped, idle connection killed at a fixed interval (close code 1006, abnormal closure) | Events arrive in bursts or never, due to buffering; stream cut at idle timeout; browser auto-reconnects | Pushes ignored or refused by the browser; disabled by default in Chrome since version 106 |
| Use for messaging | Yes, bidirectional | Yes, server to client | No: pushed responses go into the cache, not to your application code |
Practical mitigations
- Use
wss://on port 443 always. Encrypted traffic on the standard HTTPS port is the most likely to pass untouched; plainws://on port 80 is the most likely to be mangled. - Heartbeats below every idle timeout. Many load balancers and proxies drop idle connections after about 60 s by default (nginx's
proxy_read_timeoutdefaults to 60 s, for example). Send an application ping every 20 to 30 s, and raise the timeouts on infrastructure you control. - Configure your own proxies explicitly. In nginx, a WebSocket location needs
proxy_http_version 1.1;plusproxy_set_headerdirectives that pass the client'sUpgradeheader through and setConnection: upgrade, otherwise the upgrade headers are dropped. For SSE, disable response buffering (nginx honours anX-Accel-Buffering: noresponse header). - Detect and fall back. Treat the connection as working only after a first application message arrives; after repeated failures on a network, fall back to SSE plus
POST, then long polling. - Authentication through the handshake. Browsers cannot set custom headers on the WebSocket constructor, so use a cookie (and check
Originto prevent cross-site WebSocket hijacking, where a malicious page on another site opens a socket to your server and the browser attaches the victim's cookies automatically, handing the attacker a live authenticated connection) or a short-lived single-use ticket. - Deploys and draining: close connections gradually with a proper close frame, and have clients reconnect with jittered backoff (wait a random, growing amount of time before retrying, instead of a fixed delay, so thousands of clients do not all retry in the same instant), so a deploy does not look like a proxy failure to thousands of clients at once.
Worked example
A customer reports the chat widget "connects then dies every minute" from their office. Server logs show connections closing with 1006 at about 60 s on that customer's IP range only. Their proxy has a 60 s idle timeout and your app pings every 90 s. Dropping the ping interval to 25 s fixes it without a fallback. A second customer's proxy strips Upgrade entirely: the handshake gets a plain 200 response, the client never receives a welcome message, and it falls back to SSE, which also turns out to be buffered, so it lands on long polling. Both are "WebSocket doesn't work" tickets with completely different fixes.
Given the head of a singly linked list, determine whether it contains a cycle, and if so, return the node where the cycle begins, using O(1) extra space (no visited-set). Explain why moving one pointer twice as fast as the other guarantees they meet if and only if a cycle exists, and how that same meeting point lets you locate the cycle's start.
Sample Answer
Direct answer
Advance one pointer (slow) one step at a time and another (fast) two steps at a time. If the list has no cycle, fast reaches the end first and you can report there is none. If it does have a cycle, fast eventually laps slow and the two meet somewhere inside it. Once they meet, restarting one pointer at the head and advancing both pointers one step at a time makes them meet again exactly at the cycle's start. All of this uses O(1) extra space, no visited set required.
Structured elaboration
Why meeting implies a cycle, and why no meeting implies no cycle. With no cycle, fast strictly gains ground toward a null terminator every step and reaches it in at most n/2 steps; it can never occupy the same node as slow without a cycle to loop back through. Once both pointers are inside a cycle, fast closes the gap to slow by exactly one node per step, because fast gains two steps of distance while slow gains one, a net closing rate of one per step. Since the gap can never exceed the cycle's length, they are guaranteed to meet within one full lap of the cycle.
Why the meeting point locates the cycle's start. Let a be the distance from the head to the cycle's start, c be the cycle's length, and b be the distance from the cycle's start to the meeting point, with 0≤b<c. By the time they meet, slow has traveled a + b steps and fast has traveled exactly twice that, but fast has also gone around the cycle some whole number of extra laps n≥1:
So a and (c - b) differ by a whole number of cycle lengths, meaning a pointer walking one step at a time from the head, and a pointer walking one step at a time from the meeting point, land on the same node after exactly a steps: the cycle's start.
Related applications of the same fast/slow pattern. Removing the n-th node from the end of a list uses the same shape without any cycle involved: advance one pointer n steps first, then move both pointers together; when the front pointer reaches the end, the trailing pointer sits exactly at the node to remove. Finding a duplicate number hidden in an array reframes the array itself as an implicit linked list, where the value stored at each index tells you which index to visit next; a repeated value forces two different positions to point at the same next index, creating a cycle in that implicit list, which Floyd's tortoise-and-hare detects exactly the way it detects a cycle here.
Worked example
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
def detect_cycle_start(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
ptr = head
while ptr is not slow:
ptr = ptr.next
slow = slow.next
return ptr
return None
if __name__ == "__main__":
nodes = [Node(i) for i in range(5)] # values 0,1,2,3,4
for i in range(4):
nodes[i].next = nodes[i + 1]
nodes[4].next = nodes[2] # cycle back into node with value 2
start = detect_cycle_start(nodes[0])
print(start.val)
Running this prints 2. In the derivation's terms: a = 2 (two steps from the head, value 0, to the cycle's start, value 2), c = 3 (the cycle 2 to 3 to 4 back to 2 has three edges), and the two pointers first meet at the node with value 3, so b = 1 (one step from the cycle's start to that meeting point). Checking the identity: c - b = 3 - 1 = 2, which equals a, confirming the derivation against this concrete run.
Complexity
Time: O(n). The pointers meet within one full lap of the cycle once both are inside it, and finding the cycle's start afterward takes at most another full lap; both phases are bounded by a constant multiple of the list's length n.
Space: O(1), since only the slow and fast pointers (and later ptr) are held, with no visited set.
Edge cases
- Empty list (
headisNone):fastisNoneimmediately, so the loop never runs and the function correctly returns no cycle. - Single node with no self-link:
fast.nextisNoneon the first check, so the loop exits immediately with no cycle detected. - Single node that cycles to itself:
slowandfastboth land back on that same node on the first iteration, correctly reporting it as the cycle's start.
Trade-offs & pitfalls
A common bug is comparing pointer values instead of pointer identity; when list values can repeat, slow.val == fast.val can be true without slow and fast being the same node, so the check must be slow is fast.
You're weighing a real investment in your own growth, whether that's a certification, an advanced degree, or simply protecting learning time against delivery pressure. Walk me through how you'd decide it's worth it, and how you'd negotiate the time or budget to do it.
Sample Answer
Direct answer
Decide by comparing the investment's expected payoff against its real cost, which is time and attention pulled from delivery, not just money, then bring your manager a specific, time-boxed ask paired with a coverage plan rather than an open-ended request.
Structured elaboration
- Name the investment type explicitly, since the shape of the ask differs: a certification (weigh its actual return on investment, or ROI, against the time and fee cost), a formal advanced degree (a far larger, multi-year time and money commitment for a credential), an internal on-the-job rotation (trades delivery time on your current team for exposure elsewhere), or simply protecting a fixed number of weekly hours split across growth domains.
- Compute the real cost honestly. If the ask is a fixed weekly-hours budget, name explicitly what shrinks to make room for it; a request that doesn't name its own trade-off reads as costless and gets challenged later.
- The negotiation lever that works is a bounded pilot: a defined number of weeks, a specific hours-per-week figure, a defined coverage plan for what you'd otherwise be doing, and a checkpoint partway through to reassess, rather than an open-ended protected-time request.
- If the ask involves protecting time against on-call or delivery pressure specifically, address it directly: name how coverage continues (pairing, documentation, swapping on-call windows) rather than letting the ask sound like a straight subtraction from the team's capacity.
Worked example
I wanted to protect a few hours a week for a structured certification relevant to where I wanted to grow, but I didn't just ask for the time. I brought my manager a specific ask: this many hours a week, for this many months, here's exactly what shrinks to make room for it, and here's how on-call coverage stays intact while I'm doing it. I framed it as a pilot with a checkpoint partway through: if my delivery velocity dropped noticeably, we'd pause and reassess rather than quietly abandoning either the study time or the delivery commitments. That framing made it an easy yes, because the cost was explicit and bounded instead of open-ended.
Trade-offs & pitfalls
- Asking for time without naming what shrinks to make room for it is the single biggest reason these requests get pushback.
- Treating a degree, a certification, an on-the-job rotation, and simply protected weekly hours as interchangeable asks misses that they carry very different costs and need different negotiations.
- Framing the investment purely as personal benefit rather than tying it to team or delivery value makes it harder to defend when priorities tighten.
- No checkpoint means no graceful way to pause if delivery genuinely suffers; always build in a reassessment point.
You have 48 hours before your interview. Sketch a one-page research plan: which sources you'd consult, how you'd timebox each activity, and the two or three deliverables you'd walk in with to show you understand the team's product, customers, and current pain points.
Sample Answer
Direct answer
Timebox roughly six to eight total hours of prep across the two days, front-loading breadth (company, product, team) on day one and narrowing to role-specific depth and a same-day source check on day two, then walk in with three concrete deliverables: a one-page brief, a short ranked list of open questions, and one specific, current observation you can offer unprompted.
Structured elaboration
A sample timeboxed plan:
- Hours 1-2 (Day 1): company fundamentals, product, business model, recent news or funding, from the company site plus one or two independent articles.
- Hours 3-4 (Day 1): team and role specifics, a deep read of the job posting, LinkedIn for the hiring manager and current team members, the engineering or product blog if one exists.
- Hours 5-6 (Day 2): operational signals, public GitHub, app store or review sites, a status page, anything hinting at pain points.
- Hour 7 (Day 2, morning of): a live-source check, since something can change in the last 48 hours (a launch, an outage, a leadership change), and citing something that already changed is worse than not mentioning it at all.
- Hour 8: synthesis, actually writing the one-pager and the ranked question list.
Deliverables: a one-page brief (mission, likely composition, top challenges), three to five ranked open questions you'd actually ask, and one specific, current observation that proves the research is fresh rather than generic.
Worked example
Interviewing Wednesday for a Data Engineer role. Monday evening: two hours on the company site plus an article about a recent funding round. Tuesday lunch: two hours on the job posting, which repeatedly mentions "streaming pipelines," plus the hiring manager's LinkedIn, which shows a recent post about migrating off a legacy extract-transform-load (ETL, the process of pulling data from a source, transforming it, and loading it into a destination system) tool. Tuesday evening: two hours on their public GitHub, a data-quality library with recent active commits, and review sites, where a recurring theme is "great team, tooling is dated." Wednesday morning: a quick check for anything new (nothing has changed) plus writing the brief. You walk in with the brief, a ranked question list (the streaming migration's timeline first, current data-quality monitoring second), and a specific observation: noticing a recent commit adding schema validation to that data-quality library, and asking whether it's related to the ETL migration.
Trade-offs and pitfalls
The most common failure is spending all the time on breadth and none on synthesis, ending up with a lot of facts and no point of view, so timebox the synthesis step explicitly rather than letting it get crowded out. Don't manufacture a specific observation to sound prepared if you genuinely didn't find one, admitting you focused your limited time elsewhere is stronger than a vague, generic comment.
Implement a type-safe event emitter in TypeScript where the event names and payload types come from a single interface, so that a wrong event name or payload fails to compile.
Sample Answer
Direct answer
Declare one interface that maps each event name to its payload type, make the emitter generic over that interface (TypedEmitter<Events>, where a generic is a class or function with a type placeholder, filled in by whoever uses it), and type every method with a key parameter K extends keyof Events whose payload is Events[K]. The same K ties the event name argument to the payload argument, so a misspelled name or a payload of the wrong shape fails to compile. An interface is a compile-time-only description, so at runtime this is an ordinary emitter that stores arrays of handlers in an object.
The emitter
// emitter.ts
export class TypedEmitter<Events extends { [K in keyof Events]: unknown }> {
private handlers: { [K in keyof Events]?: Array<(payload: Events[K]) => void> } = {};
on<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void): () => void {
(this.handlers[event] ??= []).push(handler);
return () => this.off(event, handler);
}
off<K extends keyof Events>(event: K, handler: (payload: Events[K]) => void): void {
this.handlers[event] = this.handlers[event]?.filter((h) => h !== handler);
}
emit<K extends keyof Events>(event: K, ...args: Events[K] extends void ? [] : [payload: Events[K]]): void {
for (const h of [...(this.handlers[event] ?? [])]) {
(h as (payload?: Events[K]) => void)(args[0]);
}
}
}
How the types work:
K extends keyof Eventsis a generic parameter (a type placeholder) constrained to the interface's key names. When you callbus.on("login", ...), the compiler infersK = "login"from the string literal, and then every other occurrence ofKin the signature (Events[K]) resolves to the payload for that event only. This linking of two arguments through one type parameter is the core of the technique.Events extends { [K in keyof Events]: unknown }accepts any interface or object type. The braces form a mapped type: a type built by walking the keys of another type (K in keyof Eventsvisits each key) and giving each key a value type, hereunknown, which any value satisfies. So the constraint reads "Eventsmust be an object whose every property has some type". The more obvious constraintRecord<string, unknown>means "an object with any string key mapping to anything", and it rejects interfaces, because an interface has no index signature (a declaration such as[key: string]: unknownthat allows arbitrary string keys), so it is not assignable to a string-keyed record. WithAppEventsas an interface, tsc (strict, TypeScript 5.9.3) reportsType 'AppEvents' does not satisfy the constraint 'Record<string, unknown>'. Index signature for type 'string' is missing in type 'AppEvents'., while the mapped-type constraint accepts it.logout: voidmarks an event with no payload. The rest parameter...args: Events[K] extends void ? [] : [payload: Events[K]]is a conditional type (A extends B ? X : Y, a type-level if) that makes the payload argument required for events that have one and forbidden for events that do not. A rest parameter collects the remaining arguments into a tuple (a fixed-length array type), so the type is either the empty tuple[](no more arguments allowed) or a one-element tuple whose element carries the labelpayload, a name used only in error messages and editor hints.onreturns an unsubscribe function, which avoids the identity problem of remembering the exact handler reference to pass tooff.- Registering with
??=.(this.handlers[event] ??= []).push(handler)means: if the slot for this event isundefined, store an empty array there first; either way the parenthesised expression is the array in the slot, andpushadds the handler to it. The?in{ [K in keyof Events]?: ... }makes each slot optional, which is why the slot can beundefineduntil the firston. - One honest cast. Inside
emit, the handler array for a generic key cannot be narrowed by the compiler, so the call goes through a cast (as, which tells the compiler to treat the value as a given type without checking it) to(payload?: Events[K]) => void, andargs[0]is the payload orundefinedfor a no-payload event. The cast is confined to the implementation; callers never see it, and the public signatures are what carry the guarantee. emititerates over a copy ([...handlers]), so a handler added withonwhile an emit is running is not called until the next emit; without the copy,pushgrows the very array being looped over and the new handler runs in the same emit. Removal needs no copy:offbuilds a new array withfilter, so a handler removed during an emit still runs for that emit and is gone from the next one.
Usage and output
// usage.ts
import { TypedEmitter } from "./emitter";
interface AppEvents {
login: { userId: string };
logout: void;
cartChanged: { items: number; total: number };
}
const bus = new TypedEmitter<AppEvents>();
const stop = bus.on("login", (p) => console.log("login", p.userId.toUpperCase()));
bus.on("cartChanged", ({ items, total }) => console.log("cart", items, total.toFixed(2)));
bus.on("logout", () => console.log("logout"));
bus.emit("login", { userId: "ada" });
bus.emit("cartChanged", { items: 2, total: 19.5 });
bus.emit("logout");
stop();
bus.emit("login", { userId: "grace" });
console.log("done");
Compiled with tsc --strict and run with Node, this prints:
login ADA
cart 2 19.50
logout
done
After stop() the second login emit reaches no handler, so nothing is printed for grace. In the handler, p.userId.toUpperCase() type-checks because p is inferred as { userId: string } with no annotation.
Wrong usage that must fail
// bad.ts
import { TypedEmitter } from "./emitter";
interface AppEvents {
login: { userId: string };
logout: void;
}
const bus = new TypedEmitter<AppEvents>();
bus.emit("loginn", { userId: "ada" });
bus.emit("login", { userId: 42 });
bus.emit("login");
bus.emit("logout", { userId: "ada" });
bus.on("login", (p) => p.user);
tsc --strict --noEmit (TypeScript 5.9.3) reports:
bad.ts(10,10): error TS2345: Argument of type '"loginn"' is not assignable to parameter of type 'keyof AppEvents'.
bad.ts(11,21): error TS2322: Type 'number' is not assignable to type 'string'.
bad.ts(12,5): error TS2554: Expected 2 arguments, but got 1.
bad.ts(13,20): error TS2554: Expected 1 arguments, but got 2.
bad.ts(14,26): error TS2339: Property 'user' does not exist on type '{ userId: string; }'.
The five lines are, in order: a misspelled event name, a wrong payload type, a missing payload, a payload on a no-payload event, and a misspelled field inside a handler.
Trade-offs and pitfalls
- Compile-time only. Events coming from outside TypeScript (a
postMessagepayload, JSON) are not checked; validate them at the boundary before emitting. - Memory. A handler that is never removed keeps everything it closes over alive. Return and call the unsubscribe function when a component is torn down.
- Errors in handlers. A handler that throws stops the remaining handlers for that emit. Wrap calls in
try/catchif isolation matters; Node's ownEventEmitterbehaves the same way for synchronous listeners. - Alternatives. Node's
EventEmitterand the DOM'sEventTargetare untyped by default; wrapping them with the same generic signatures gives the same checking without a custom class.
Running the code
npm i typescript@5
npx tsc --strict --module commonjs --target es2022 --outDir out emitter.ts usage.ts
node out/usage.js
npx tsc --strict --noEmit --module commonjs --target es2022 bad.ts
Find and fix the bug in this JavaScript async function, where a missing await causes unpredictable ordering and errors:
async function processItems(items, processor) {
items.forEach(async item => {
await processor(item);
});
console.log('done');
}
Explain the root cause and provide a corrected version that guarantees 'done' prints only after every item has been processed.
Sample Answer
Direct answer
Array.prototype.forEach does not await its callback: it fires each async callback and moves on immediately, so console.log('done') runs before any of the await processor(item) calls have resolved. The fix is to replace forEach with a construct that actually waits, either a for...of loop with await inside it (sequential) or Promise.all over items.map(...) (concurrent).
Structured elaboration
forEach was designed before async/await existed and its callback's return value, including a Promise, is simply discarded. Passing an async function as the callback doesn't change this: each invocation still returns a Promise that forEach never looks at, so forEach itself completes synchronously (having merely started every item, not finished any of them) the instant it has called the callback once per array element. The console.log('done') line after the forEach call then runs immediately, while the async work is still in flight in the background.
Worked example
async function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
// Fixed, distinct per-item delays (not Math.random()) so the interleaving below
// is deterministic and reproduces identically on every run, not just illustrative.
const delays = { 1: 20, 2: 10, 3: 30 };
// BUGGY
async function processItemBuggy(x) { await sleep(delays[x]); console.log(' processed', x, '(buggy)'); }
async function processBuggy(items) {
items.forEach(async item => { await processItemBuggy(item); });
console.log('done (buggy)');
}
// FIXED: sequential
async function processItemFixed(x) { await sleep(delays[x]); console.log(' processed', x, '(fixed)'); }
async function processFixed(items) {
for (const item of items) { await processItemFixed(item); }
console.log('done (fixed)');
}
(async () => {
console.log('--- buggy run ---');
await processBuggy([1, 2, 3]);
await sleep(100); // let the buggy run's background work finish before the next section starts
console.log('--- fixed run (sequential for-of) ---');
await processFixed([1, 2, 3]);
})();
Executed output (buggy items finish asynchronously in the background; with the fixed per-item delays above, item 2 always resolves first, then item 1, then item 3, after done has already printed):
--- buggy run ---
done (buggy)
processed 2 (buggy)
processed 1 (buggy)
processed 3 (buggy)
--- fixed run (sequential for-of) ---
processed 1 (fixed)
processed 2 (fixed)
processed 3 (fixed)
done (fixed)
done (buggy) prints immediately, before any processed line: forEach fired all three async callbacks and moved on without waiting for any of them. The processed (buggy) lines do eventually print, once their fixed delays resolve, in delay order (2, then 1, then 3, not the input order), rather than before done. The for...of version correctly prints all three processed lines, strictly in input order, before done.
Trade-offs and pitfalls
There are two valid fixes with different semantics, and picking the wrong one is itself a common mistake: a for...of loop processes items strictly one at a time (useful when order matters or you must not overwhelm a downstream dependency with concurrent calls), while await Promise.all(items.map(item => processor(item))) processes all items concurrently and finishes as soon as the slowest one does (faster, but only safe if the operations are independent and the downstream system can handle concurrent load). Silently reaching for forEach out of habit, rather than deliberately choosing sequential versus concurrent semantics, is exactly how this bug class gets reintroduced even by developers who already know the rule.
Describe flame graphs and how to read them to identify CPU hotspots. Explain what the X and Y axes represent, what wide vs tall flames indicate, and how inlined functions or shared libraries affect interpretation when prioritizing optimizations.
Sample Answer
What a flame graph is
A flame graph is a visualization built from many CPU stack samples collapsed together, showing which call stacks were running and how often.
The axes
- X-axis is NOT time. Boxes are typically sorted alphabetically (or by tool convention) left to right, and a box's WIDTH represents how often that function appeared across all samples, i.e. its share of total CPU time. Wide = expensive.
- Y-axis is call-stack depth. The bottom row is the root (e.g. a thread's entry point or
main), and each box stacked directly above another is a function CALLED BY the box below it. Moving up the stack means descending deeper into callees.
Wide vs tall
- A wide, flat "plateau" (a box that is wide but has no boxes stacked above it, or only thin ones) means that function itself is doing expensive work, it is a leaf-level hotspot.
- A tall, narrow "tower" (many boxes stacked on top of each other, each fairly narrow) shows a deep call chain, lots of nested calls, but tallness alone does not mean expensive; a narrow tower can represent very little total CPU time even though it looks visually striking.
How inlining and shared libraries distort the picture
- A JIT (Just-In-Time compiler, one that compiles code to machine instructions while the program runs) or an ahead-of-time compiler will often inline small, frequently-called functions directly into their caller for speed. An inlined function may not appear as its own box at all, its cost gets folded into the caller, making the caller look more expensive than its own source code would suggest.
- Frames from shared libraries without debug symbols can show up as raw addresses or a single generic library name (e.g. everything collapsing into one
libcbox), hiding what is really many distinct functions behind one wide box. Loading proper symbol tables (or using a profiler build with symbols) is often needed before a flame graph is trustworthy for prioritization.
Worked example
Picture a flame graph with main at the bottom spanning 100% of the width, calling handle_request (also ~100% width, since it wraps almost the whole request), which splits into two children: parse_json (10% width) and render_template (85% width). Inside render_template, there is a leaf box format_currency at 60% width with nothing stacked above it. That plateau tells you format_currency itself, not something it calls, is the single best optimization target, it accounts for more CPU than everything else in the request combined.
How would you evaluate, as a candidate, whether a company's published culture and values are actually practiced day to day rather than just marketing? What would you look for, and what would you ask during the interview process to find out?
Sample Answer
Direct answer
I treat a company's published culture and values as a claim to be tested, not a fact to accept, and I look for evidence in three places: how people describe real, specific incidents (not slogans) when I ask about them, whether the org's actual structures and incentives would make the stated behavior easy or hard to practice, and whether the story is consistent across different people I talk to in the process.
Structured elaboration
- Ask for a specific recent incident, not a description of the value. A question like "tell me about a time the team had to choose between shipping fast and following the documented review process" forces a real story; a question like "how would you describe the engineering culture here" invites a rehearsed, values-page-adjacent answer that tells you little.
- Check whether the org's structure actually supports the stated value, independent of what anyone says. If a company claims to value psychological safety but every interviewer you meet is visibly guarded about naming any team problem, or if a company claims strong autonomy but every technical decision in the loop turns out to require a director's sign-off, the structural evidence contradicts the claim regardless of the wording used to describe it.
- Triangulate across multiple people, ideally at different levels and tenures. A single enthusiastic interviewer proves little; a hiring manager, a peer-level engineer, and someone from a different function independently describing the same specific behavior (not the same slogan) is much stronger evidence.
- Ask what the company would do differently if it stopped believing the value, and watch for a concrete, structural answer versus a vague one. People who work inside a genuinely lived value can usually name a real trade-off it costs them; people describing marketing usually cannot.
- Treat your own discomfort as data. If a described norm (pace, feedback directness, decision-making style) makes you visibly uneasy during the process itself, that is a more reliable signal about fit than anything printed on the careers page, because it is your own live reaction rather than a claim you are being asked to evaluate secondhand.
Worked example
Suppose a company's careers page says it "empowers engineers with high autonomy." During the loop, ask the hiring manager for a specific recent example: "Tell me about the last time an engineer on this team made a production architecture decision without it going through a review committee first." A genuine, lived-autonomy answer sounds like: "Last quarter one of our engineers decided independently to switch a service from synchronous to async processing after noticing latency complaints; she looped in two people for a sanity check, shipped it, and reported the outcome in the next team sync." A marketing-only answer sounds like: "We really believe in empowering our engineers," repeated with no specific incident when pressed twice. If a peer engineer you speak to separately can also describe a comparable specific incident in their own words, that consistency is strong corroborating evidence; if the hiring manager's story turns out to be the ONLY example anyone can produce company-wide, that is itself informative about how common the behavior actually is.
Trade-offs & pitfalls
The main failure mode is accepting an interviewer's fluent, confident description of the culture as sufficient evidence on its own; confidence and specificity are not the same thing, and a well-rehearsed answer to a values-page question is exactly what a company under-delivering on its stated culture is most likely to have prepared. A second pitfall is over-weighting a single glowing anecdote from one enthusiastic interviewer without checking whether it generalizes; one great story is an anecdote, not a pattern. A third is treating any inconsistency you find as automatically disqualifying: it is normal for a large or growing organization to have real variance across teams, so the useful conclusion is usually about the SPECIFIC team and manager you'd actually join, not the company as a monolithic whole.
Implement a React ErrorBoundary component that logs errors to a provided logger (for example, an error-tracking service like Sentry) and displays a localized fallback UI when a child component throws during render. Then write a React Testing Library test that asserts the logger was called and that the fallback text is rendered. Explain what an ErrorBoundary will and will not catch, and discuss the trade-off between showing a retry UI and surfacing the raw error to the user.
Sample Answer
Direct answer
A React error boundary catches rendering errors thrown by any component in its subtree during render, in lifecycle methods, and in constructors, logs the error with enough context to diagnose it, and shows a fallback UI instead of leaving the user with a blank screen or React's own default error overlay; it does not catch errors in event handlers, asynchronous code, or errors thrown in the boundary component itself.
Structured elaboration
What it catches. Errors thrown during the render phase of any component below the boundary in the tree, including errors in lifecycle methods (componentDidMount, etc.) and in constructors. This is React's mechanism for preventing one broken component from crashing the entire application.
What it does NOT catch, and why that matters. Event handlers (a click handler that throws is a normal JavaScript exception, not a React rendering error, and needs its own try/catch); asynchronous code (a .then() callback or an async function's rejection happens outside React's render cycle entirely); server-side rendering errors; and errors thrown by the error boundary component itself (a boundary cannot catch its own failures, which is why the boundary component should be kept as simple as possible, with minimal logic that could itself throw).
Logging to an error-tracking service. componentDidCatch(error, info) receives both the error object and a componentStack describing which component tree led to the failure; sending both to a service like Sentry, tagged with any available user or session context, turns "a customer reported a blank page" into "we can see exactly which component threw, with what stack, for which user" without waiting for the customer to describe what they were doing.
Retry UI versus surfacing the raw error. A "try again" button that resets the boundary's state and re-attempts rendering the subtree is appropriate when the failure might be transient (a component that failed because of a momentary bad prop from a slow API response); it is misleading for a deterministic bug that will fail identically on every retry, where a generic "something went wrong, we've been notified" message (with no false promise that retrying will help) is more honest to the user, even though it is less satisfying than a button that appears to offer control.
Worked example
class ErrorBoundary extends React.Component {
constructor(props) { super(props); this.state = { hasError: false }; }
static getDerivedStateFromError(error) { return { hasError: true }; }
componentDidCatch(error, info) {
if (this.props.logger) this.props.logger.logError(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return <div role="alert">{this.props.fallbackText || 'Something went wrong.'}</div>;
}
return this.props.children;
}
}
Executed (React Testing Library, verified): rendering <ErrorBoundary logger={logger} fallbackText="We hit a snag. Please retry."><Boom /></ErrorBoundary>, where Boom throws during render, confirms screen.getByRole('alert') shows the fallback text and logger.logError was called exactly once with the thrown Error object. A second test confirms that when no child throws, the boundary renders its children normally and logger.logError is never called, so the boundary is confirmed to be transparent in the non-error case, not just functional in the error case.
Trade-offs and pitfalls
A single application-wide error boundary at the root catches everything but takes down the ENTIRE page for a failure in one small, non-critical widget; placing boundaries around individual independent sections (a sidebar widget, a comments section) means one broken component degrades gracefully to just that section showing a fallback, while the rest of the page keeps working, which is almost always the better default for anything with multiple independent sections. The most common mistake is assuming an error boundary catches an async data-fetching failure inside a useEffect: it does not, since that error occurs outside the render phase entirely, and needs its own explicit error state managed by the component, separate from the boundary mechanism.
Recommended Additional Resources
- LeetCode (https://leetcode.com/) - Medium level JavaScript problems and UI component challenges
- GreatFrontEnd (https://www.greatfrontend.com/) - Comprehensive frontend interview prep with curated problems
- System Design Primer (https://github.com/donnemartin/system-design-primer) - Adapted for frontend architecture thinking
- Frontend Interview Handbook (https://www.frontendinterviewhandbook.com/) - Comprehensive guide specific to frontend roles
- Cracking the Coding Interview (Book by Gayle Laakmann McDowell) - Classic reference with applicable JavaScript examples
- MDN Web Docs (https://developer.mozilla.org/) - Authoritative resource for JavaScript, CSS, HTML, and APIs
- React Documentation (https://react.dev/) - Official React docs with deep dives into hooks and performance
- Web.dev (https://web.dev/) - Google's resource for modern web development and performance optimization
- JavaScript.info (https://javascript.info/) - Comprehensive JavaScript tutorial and reference
- CSS Tricks (https://css-tricks.com/) - Practical CSS knowledge and best practices
- Performance Auditing with Chrome DevTools (practice using Lighthouse, Performance tab for optimization analysis)
- WCAG 2.1 Guidelines (https://www.w3.org/WAI/WCAG21/quickref/) - Accessibility standards
- Frontend Masters courses - Advanced JavaScript, React performance, system design for frontend
Search Results
34 Front-End Interview Questions (With Sample Answers) - Indeed
What projects have you designed front-end for? · Which of your previous front-end projects would you say you're most proud of? · Have you had any experience in ...
Top 35+ UI Developer Interview Questions and Answers for 2026
Basic UI Developer Interview Questions · 1. What exactly is the role of a UI developer? · 2. What's the difference between a UI developer and a UX developer? · 3.
Introduction | The Official Front End Interview Handbook 2025
Complete frontend developer interview guide: JavaScript coding questions, UI components, system design, quiz prep & expert tips from ex FAANG engineers.
Top Frontend Developer Interview Questions and Answers - Intellipaat
1. Define HTML. How does front-end development employ it? Simply put, Hypertext Markup Language (HTML) is a markup language that is utilized for creating web ...
React JS Interview Questions ( Multi Step Form ) - YouTube
React JS Interview Questions ( Multi Step Form ) - Frontend Machine Coding Interview ... Frontend Interview Questions Mid/Senior Level. theSeniorDev•143K views.
50+ Essential Vue Interview Questions & Answers (Easy to Advanced)
Use this list of Vue interview questions and answers to prepare for your upcoming meeting with a tech recruiter or lead front-end engineer!
Crack Any Frontend Interview: Ultimate Prep Guide - YouTube
... interview questions UI developer infosys react developer infosys frontend developer infosys UI developer. ... Frontend Interview Questions Mid/Senior Level.
This interview preparation guide was generated using AI-powered research from the sources listed above. While we strive for accuracy, we recommend verifying critical information from official company sources.
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