);\n } else {\n res.end(/(^|;\\s*)sid=1/.test(req.headers.cookie || '') ? 'sent' : 'missing');\n }\n}).listen(4100);\n\nconst PROFILES = {\n 'chromium': async () => { const b = await chromium.launch(); return [await b.newContext({ ignoreHTTPSErrors: true }), () => b.close()]; },\n 'chromium+phaseout': async () => { const b = await chromium.launch({ args: ['--test-third-party-cookie-phaseout'] }); return [await b.newContext({ ignoreHTTPSErrors: true }), () => b.close()]; },\n 'chromium+legacy': async () => { const b = await chromium.launch({ args: ['--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure'] }); return [await b.newContext({ ignoreHTTPSErrors: true }), () => b.close()]; },\n 'firefox': async () => { const b = await firefox.launch(); return [await b.newContext({ ignoreHTTPSErrors: true }), () => b.close()]; },\n 'firefox+TCP pref': async () => { const b = await firefox.launch({ firefoxUserPrefs: { 'network.cookie.cookieBehavior': 5 } }); return [await b.newContext({ ignoreHTTPSErrors: true }), () => b.close()]; },\n 'webkit': async () => { const b = await webkit.launch(); return [await b.newContext({ ignoreHTTPSErrors: true }), () => b.close()]; },\n};\n\nasync function widgetSees(context, site, v, set) {\n const page = await context.newPage();\n await page.goto(${site}/embed?v=${encodeURIComponent(v)}&set=${set});\n const frame = page.frames().find((f) => f.url().includes('/widget'));\n await frame.waitForFunction(() => window.result !== undefined);\n const out = await frame.evaluate(() => window.result);\n await page.close();\n return out;\n}\n\nconst names = Object.keys(PROFILES);\nconst row = (label, cells) => console.log(label.padEnd(28) + cells.map((c) => c.padEnd(20)).join(''));\n\nconsole.log('A. cookie set and read inside one embedding site');\nrow('cookie attributes', names);\nfor (const v of Object.keys(VARIANTS)) {\n const cells = [];\n for (const n of names) { const [ctx, close] = await PROFILESn; cells.push(await widgetSees(ctx, SITE_A, v, 1)); await close(); }\n row(v, cells);\n}\nconsole.log('\\nB. cookie set under site A, then read when the widget is embedded on site B');\nrow('cookie attributes', names);\nfor (const v of ['None; Secure', 'None; Secure; Partitioned']) {\n const cells = [];\n for (const n of names) {\n const [ctx, close] = await PROFILESn;\n await widgetSees(ctx, SITE_A, v, 1);\n cells.push(await widgetSees(ctx, SITE_B, v, 0));\n await close();\n }\n row(v, cells);\n}\nprocess.exit(0);\n\nRun in the Playwright 1.48.2 container (Chromium 130, Firefox 131, WebKit 18.0), it printed the same table on each of 10 runs:\n\nA. cookie set and read inside one embedding site\ncookie attributes chromium chromium+phaseout chromium+legacy firefox firefox+TCP pref webkit \nNone; Secure sent sent sent sent sent missing \nNone (no Secure) missing missing missing missing missing missing \nno SameSite missing missing missing sent sent missing \nNone; Secure; Partitioned sent sent sent sent sent missing \n\nB. cookie set under site A, then read when the widget is embedded on site B\ncookie attributes chromium chromium+phaseout chromium+legacy firefox firefox+TCP pref webkit \nNone; Secure sent sent sent sent missing missing \nNone; Secure; Partitioned missing missing missing sent missing missing \n\nHow to read the tables: each row is a Set-Cookie header the widget sends, each column is a browser profile, and each cell is what the widget's own server received when the widget called it. sent means the cookie came back, so the widget can recognise the signed-in user. missing means the server saw no cookie; in a real product that is the user who looks signed out inside the embed, or a sign-in loop that starts over. Table A sets and reads the cookie under one embedding site. Table B sets it under site A, then loads the widget under site B (the single-sign-on case).\n\nHow the script produces them:\n\napp-a.test, app-b.test and widget.test are three different sites. The --add-host name:127.0.0.1 options in the run command point all three at loopback, so one Node server on port 4100 can play every role.\nSecure cookies are only stored and sent over HTTPS, so openssl creates a throwaway self-signed certificate valid for the three names (subjectAltName), and ignoreHTTPSErrors: true lets each browser accept it.\nThe server has three routes. /embed returns a page containing an iframe for the widget. /widget sets the cookie (when set=1) and runs a fetch to /whoami with credentials: 'include'. /whoami answers sent or missing from the request's Cookie header. That fetch is cross-site because the page in the address bar belongs to a different site from the widget.\nwidgetSees opens the embedding page, finds the widget frame and waits for window.result to exist, so it waits for a condition instead of sleeping.\nTwo Chromium profiles pass command-line switches; firefox+TCP pref sets network.cookie.cookieBehavior to 5, which Mozilla's cookie service defines as BEHAVIOR_REJECT_TRACKER_AND_PARTITION_FOREIGN (block known trackers, partition other third-party cookies).\n\nWhat the tables show:\n\n1. Chrome-family behaviour matches the docs. None; Secure is returned; None without Secure is not (every engine here refused it); a missing SameSite is not returned in the cross-site iframe, as the Lax default predicts.\n2. The no SameSite row differs by engine. Firefox returns the cookie (sent); Chromium and this WebKit build do not (missing). A widget that forgets SameSite therefore looks fine in Firefox and breaks for Chrome users. A suite that ran only in Firefox would pass; one that ran only in Chromium would fail but would say nothing about how Firefox or Safari treat the same cookie. Running every engine catches the bug each one alone would hide.\n3. Partitioned (CHIPS) cookies isolate per embedding site. In Chromium and in Firefox with the pref from finding 4, the cookie set under site A is not visible under site B (table B, missing); a plain None; Secure cookie is shared in Chromium (sent), which is exactly what privacy-restricted browsers stop.\n4. Playwright's bundled Firefox does not match retail Firefox. By default the cross-site cookie crossed from A to B (sent). Launching with the pref network.cookie.cookieBehavior set to 5 (the value that turns on Total Cookie Protection's partitioning) produces missing, so the CI profile must set it.\n5. This WebKit build returned no third-party cookie in any variant. That fits Safari's documented default, but it is a Playwright WebKit build, not Safari, so use it as an early alarm and verify on real Safari (macOS and iPhone) before concluding.\n6. Neither the documented Chrome flag --test-third-party-cookie-phaseout nor the legacy-behaviour feature switches changed anything in this Chromium build (the chromium+phaseout and chromium+legacy columns equal plain chromium). The block-third-party lane for Chrome therefore needs branded Chrome or Chrome for Testing configured through the vendor's documented setting, not this bundled build.\n\nTurning it into automated tests\n\n1. Contract test on the header (no browser): the widget's Set-Cookie must contain SameSite=None; Secure, and Partitioned if you adopt CHIPS. It fails the build in seconds if someone changes the cookie helper.\n2. Expectation matrix per engine: keep the table above as data (variant x profile -> sent|missing) and assert it in one test per Playwright project. A browser upgrade that changes policy then fails a named cell instead of a vague login timeout.\n3. End-to-end sign-in test: log in inside the embedded widget, reload the host page, and assert the widget still shows the signed-in state; run with and without third-party cookies. Failures here tell you the session did not survive, which is the production symptom.\n4. Real Safari lane: the same flow on real Safari (a Mac runner or a device cloud with real iPhones), because ITP details such as the seven-day storage cap are not reproduced by Playwright's WebKit.\n\nEnvironments for legacy and modern policy\n\nLane | Represents | How\n\nChromium default | Chrome today (third-party allowed, Lax default) | Playwright Chromium\nChrome with blocking | Third-party cookies blocked | branded Chrome with the setting or flag Google documents\nFirefox default | An older, permissive profile (no Lax default, no partitioning in this build) | Playwright Firefox\nFirefox with Total Cookie Protection | Retail Firefox | firefoxUserPrefs: {'network.cookie.cookieBehavior': 5}\nWebKit plus real Safari | Safari tracking prevention | Playwright WebKit as the fast check, real Safari to decide\nOld browser versions | Pre-SameSite-default behaviour | a cloud grid that offers those versions\n\nFixing the product\n\nAsk one question: must a user who signed in through the widget on site A also be signed in on site B? If no, use a partitioned cookie, the smallest change. If yes, use the Storage Access API, or avoid third-party state altogether. Commit to one:\n\nSession only matters inside each host site: SameSite=None; Secure; Partitioned. Each embedder gets its own cookie and table B's isolation is the intended behaviour. It is not a universal fix: in table A the Playwright WebKit column returned no cookie for this variant either, so confirm on real Safari, and use the Storage Access API for any browser where the partitioned cookie does not come back.\nOne login shared across many sites: the Storage Access API. document.requestStorageAccess() must be called from a user gesture in a secure context; browsers may prompt (Safari prompts for every embed that has not received access, Firefox after a threshold), the grant is stored per top-level and embedded site pair, and an iframe with the sandbox attribute (which removes powers unless tokens give them back) needs the allow-storage-access-by-user-activation token.\nAvoid the problem when you can: serve the widget from a subdomain of the host site (same site, so it is first-party) or sign in through a top-level redirect or a popup window and hand the widget a token.\n\nRunning the code\n\nsave cookies.mjs and a package.json containing {\"type\":\"module\"} in one folder, then:\ndocker run --rm --ulimit core=0 --add-host app-a.test:127.0.0.1 --add-host app-b.test:127.0.0.1 \\\n --add-host widget.test:127.0.0.1 -v \"$PWD\":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy sh -c \\\n 'npm i --silent playwright@1.48.2 && timeout 300 node cookies.mjs'"}},{"@type":"Question","name":"What's a lesson from this project that changed how you approach your work since?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nPick one specific lesson, not a list, and show the before-and-after: what you used to do, the incident that exposed the gap, and the concrete habit or process change you adopted afterward. The proof of a real lesson is that you can point to it showing up again in later work, not just that you felt bad about the original mistake.\n\nHow to select and structure the story\n\nSelection criteria: the lesson should trace to a specific, nameable trigger (not a vague realization), change something observable about how you work (a habit, a checklist item, a review step), and still be in effect, meaning you'd tell the same story about how you work today.\n\nStructure:\n1. Trigger: the specific moment that exposed the gap.\n2. Insight: what you concluded caused it.\n3. Change: the concrete new habit or process you adopted.\n4. Persistence: evidence the change stuck, ideally a later instance where it helped.\n\nWorked example (skeleton)\n\nTrigger: shipped a change without a documented rollback path, and when it caused an issue, the team spent a weekend improvising a fix under pressure. Insight: the gap wasn't the bug itself, it was that \"how do we undo this\" had never been asked before launch. Change: added a rollback-plan line item to the launch checklist, required before any release review sign-off. Persistence: in the next several launches, the checklist step surfaced two cases where no clean rollback existed, and the team fixed that before shipping instead of during an incident.\n\nTrade-offs and pitfalls\n\nAvoid lessons that are humble-brags in disguise (\"I learned I care too much about quality\"); interviewers see through this.\nAvoid lessons disconnected from an observable behavior change; \"I learned to communicate better\" without a concrete mechanism is not verifiable.\nDon't pick a lesson that undermines the core competency the role needs, unless you can show it's fully resolved.\nA senior answer distinguishes a lesson from a regret: a lesson changed your process going forward, a regret is just something you wish had gone differently."}},{"@type":"Question","name":"You are reviewing a component library and find three recurring accessibility problems: clickable divs, icon-only buttons with no text, and focus that disappears when a panel opens. For each, show the markup fix and explain what a keyboard or screen-reader user experiences before and after.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\nAll three problems have a markup-level fix, and the fixes are small. Clickable divs become | Tab reaches it; Enter and Space each click it once\nIcon-only button | The accessibility tree holds a button whose name is the empty string, so the control has no name | aria-label=\"Close\" on the button plus aria-hidden=\"true\" on the , or Search | The tree holds buttons named \"Close\" and \"Search\"\nPanel steals focus | The open trigger is hidden while focused, document.activeElement falls to , and the next Tab lands somewhere the user did not choose | and one showModal() call | Focus moves into the dialog, six Tab presses never reach the page behind, Escape closes it and focus is back on the trigger\n\nFix 1: clickable divs\nA div has no role and no tab stop. tabindex=\"0\" and role=\"button\" plus key handlers can imitate a button, but a native \n \n \n\n

After

\n \n \n \n \n \n

Filters

\n \n \n
\n

Link behind the panel

\n \n\n \n\n\n\nThe test runs in Chromium, Firefox and WebKit (Playwright's WebKit build; this is not Safari). It asserts the Tab stops, the click counts, the accessible names read from the accessibility tree (exactly one empty name, which is the unfixed icon button, plus \"Close\" and \"Search\"), the visually hidden box size, where focus goes before and after, that six Tab presses never reach the link behind the dialog, that Escape returns focus to the opener, and the outline. Three mutations (deliberately changing the markup to prove a check can fail) show the checks do work: replacing the div with a '));\n const mutDivClicks = await divKeyboardClicks();\n check(mutDivClicks === 2, ${name} mutation div-as-button should give 2 clicks, got ${mutDivClicks});\n result.divAsButtonClicks = mutDivClicks;\n await page.setContent(noRule);\n await page.focus('#a-open'); await page.keyboard.press('Shift+Tab'); await page.keyboard.press('Tab');\n result.outlineWithoutRule = await page.$eval('#a-open', (el) => getComputedStyle(el).outlineStyle);\n check(result.outlineWithoutRule === 'none', ${name} mutation outline);\n\n console.log(name, JSON.stringify(result));\n await b.close();\n}\nconsole.log(failures === 0 ? 'ALL CHECKS PASSED' : ${failures} FAILURES);\nprocess.exit(failures ? 1 : 0);\n\nOutput (the script above run in the Playwright 1.48.2 image; the lines were identical across repeated runs). The keys are the measurements: tabStops is where three Tab presses land, names is the name of every button in the accessibility tree (the single \"\" is the unfixed icon button), beforeFocus and tabAfterLoss are the focus owner after the unfixed panel opens and after one more Tab, afterFocus is where showModal() puts focus, and afterEscape is where focus returns:\n\nchromium {\"tabStops\":\"b-icon>b-open>a-btn\",\"buttonClicks\":2,\"divClicks\":0,\"names\":\"[\\\"\\\",\\\"Open filters\\\",\\\"Save\\\",\\\"Close\\\",\\\"Search\\\",\\\"Open filters\\\"]\",\"visuallyHiddenBox\":\"1x1\",\"beforeFocus\":\"BODY\",\"tabAfterLoss\":\"b-close\",\"afterFocus\":\"a-stock\",\"tabLeaksToBackground\":false,\"afterEscape\":\"a-open\",\"outline\":\"3px solid\",\"divAsButtonClicks\":2,\"outlineWithoutRule\":\"none\"}\nfirefox {\"tabStops\":\"b-icon>b-open>a-btn\",\"buttonClicks\":2,\"divClicks\":0,\"names\":\"[\\\"\\\",\\\"Open filters\\\",\\\"Save\\\",\\\"Close\\\",\\\"Search\\\",\\\"Open filters\\\"]\",\"visuallyHiddenBox\":\"1x1\",\"beforeFocus\":\"BODY\",\"tabAfterLoss\":\"b-close\",\"afterFocus\":\"a-stock\",\"tabLeaksToBackground\":false,\"afterEscape\":\"a-open\",\"outline\":\"3px solid\",\"divAsButtonClicks\":2,\"outlineWithoutRule\":\"none\"}\nwebkit {\"tabStops\":\"b-icon>b-open>a-btn\",\"buttonClicks\":2,\"divClicks\":0,\"names\":\"[\\\"\\\",\\\"Open filters\\\",\\\"Save\\\",\\\"Close\\\",\\\"Search\\\",\\\"Open filters\\\"]\",\"visuallyHiddenBox\":\"1x1\",\"beforeFocus\":\"BODY\",\"tabAfterLoss\":\"b-icon\",\"afterFocus\":\"a-stock\",\"tabLeaksToBackground\":false,\"afterEscape\":\"a-open\",\"outline\":\"3px solid\",\"divAsButtonClicks\":2,\"outlineWithoutRule\":\"none\"}\nALL CHECKS PASSED\n\nTrade-offs and pitfalls\naria-label replaces visible text. Put it on controls with no visible text. On a button that already shows \"Close\", aria-label adds a second source of text that can drift from the visible words; use it for icon-only controls.\nA is the markup answer, not the whole component. The JavaScript step is just the showModal() call and, if the app removes or re-renders the trigger, restoring focus to a sensible element yourself, since focus return is only helpful when the opener still exists. Widget-level focus management belongs to the component's own code.\nNative is not a closed loop. The specification only makes the rest of the document inert, so the dialog's controls are the only page content Tab can reach, but the browser's own interface (address bar, toolbar) sits outside the document. In a normal window, Tab past the last control can move focus there instead of wrapping to the first control; the W3C ARIA Authoring Practices discussion of this (w3c/aria-practices issue 1772) records that native dialogs do not wrap. The headless browsers used in the test have no such interface, so the test can show only that the page behind is unreachable (six Tab presses never reach the link), not that focus cycles. Do not claim a closed loop unless you have written one and tested it in a headed browser.\nDo not suppress the Escape default with a key handler that swallows it, or keyboard users lose the way out.\nLibrary rollout. Fix these three in the shared component so every consumer inherits the repair, and add the Playwright checks above to the component's test suite so a change that removes a label or reintroduces outline: none fails.\n\nRunning the code\nmkdir demo && cd demo && echo '{\"type\":\"module\"}' > package.json\nsave library.html and library-test.mjs from above into this folder\ndocker run --rm -v \"$PWD\":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \\\n sh -c 'npm i playwright@1.48.2 && node library-test.mjs'"}},{"@type":"Question","name":"Take an outer div containing an inner div containing a button, with listeners on all three, some registered for capture and some for bubble. Describe the order they fire in and how you would change it.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nA click on the button runs in three phases. First the capture phase: the event travels from the top (the window object, the browser's global object and the topmost place an event passes through, then the document) down through the outer div and the inner div toward the button, firing listeners registered with capture: true. Then the target phase at the button itself. Then the bubble phase: back up through the inner div, the outer div and the document, firing the normal (non-capture) listeners. So with capture listeners on all three elements and bubble listeners on all three, the order is outer-capture, inner-capture, button listeners, inner-bubble, outer-bubble. To change the order you choose the phase when you register (addEventListener(type, fn, { capture: true })), and you cut the journey short with stopPropagation() or stopImmediatePropagation().\n\nOrder, including a trap at the target\n\nThe DOM specification's dispatch algorithm (the step-by-step procedure the browser follows to deliver an event) walks the event path (the list of nodes from window down to the clicked element) twice: once in reverse (top to target) invoking only capture listeners, then once forward (target to top) invoking only non-capture listeners. For the target itself both passes include it, so capture listeners on the target run before bubble listeners on the target, whatever order they were registered in. In the script the button's bubble listener is registered first and its capture listener second, and the capture one still fires first.\n\n// propagation_order.mjs\nimport { chromium, firefox, webkit } from 'playwright';\nimport assert from 'node:assert/strict';\n\nconst html =
;\n\n// Registers the same listeners every time, applies one extra change, clicks the button, returns the firing order\nasync function run(page, extra) {\n return page.evaluate((extraSrc) => {\n const log = [];\n const $ = (id) => document.getElementById(id);\n const on = (target, label, capture, handler) =>\n target.addEventListener('click', (e) => { log.push(label); handler?.(e); }, capture);\n on(document, 'document-capture', true);\n on($('outer'), 'outer-capture', true);\n on($('inner'), 'inner-capture', true);\n on($('btn'), 'btn-bubble-listener', false); // registered first\n on($('btn'), 'btn-capture-listener', true); // registered second\n on($('inner'), 'inner-bubble', false);\n on($('outer'), 'outer-bubble', false);\n on(document, 'document-bubble', false);\n new Function('$', 'on', extraSrc)($, on);\n $('btn').click();\n return log.join(' > ');\n }, extra);\n}\n\nfor (const [name, type] of Object.entries({ chromium, firefox, webkit })) {\n const browser = await type.launch();\n const fresh = async () => { const p = await browser.newPage(); await p.setContent(html); return p; };\n\n const plain = await run(await fresh(), '');\n console.log(name, 'plain :', plain);\n // At the target itself, capture listeners run before bubble listeners, whatever the registration order\n assert.equal(plain, 'document-capture > outer-capture > inner-capture > btn-capture-listener > ' +\n 'btn-bubble-listener > inner-bubble > outer-bubble > document-bubble');\n\n const stopCapture = await run(await fresh(),\n \"on($('inner'), 'inner-capture-stop', true, (e) => e.stopPropagation());\");\n console.log(name, 'stop in inner capture:', stopCapture);\n assert.ok(stopCapture.includes('inner-capture-stop'));\n assert.ok(!stopCapture.includes('btn') && !stopCapture.includes('bubble'));\n\n const stopBubble = await run(await fresh(),\n \"on($('btn'), 'btn-stop', false, (e) => e.stopPropagation());\");\n console.log(name, 'stop at button :', stopBubble);\n assert.ok(stopBubble.includes('btn-stop') && !stopBubble.includes('inner-bubble'));\n assert.ok(stopBubble.includes('document-capture')); // the capture phase had already happened\n await browser.close();\n}\n\nReading the script: on(target, label, capture, handler) is a small wrapper over addEventListener('click', ...) whose last argument to addEventListener is the capture flag (true means listen during the capture phase, false during the bubble phase). When the listener fires it pushes its label onto log and then calls handler?.(e), where ?. means \"call it only if a handler was passed\". The line new Function('$', 'on', extraSrc)($, on) builds a function from the string given for each scenario, with two parameters named $ and on, and immediately calls it with the page's own helpers, so every scenario can register one extra listener (for example one that calls stopPropagation()) without repeating the setup. $('btn').click() then dispatches a click on the button, which travels the same capture, target and bubble path as a user's click, and log.join(' > ') turns the recorded labels into the order printed below.\n\nOutput (Chromium; Firefox and WebKit print the same lines. Playwright's WebKit is the engine Safari is built on, not Safari itself):\n\nchromium plain : document-capture > outer-capture > inner-capture > btn-capture-listener > btn-bubble-listener > inner-bubble > outer-bubble > document-bubble\nchromium stop in inner capture: document-capture > outer-capture > inner-capture > inner-capture-stop\nchromium stop at button : document-capture > outer-capture > inner-capture > btn-capture-listener > btn-bubble-listener > btn-stop\n\nThe first line is the full order for the plain case: document-capture > outer-capture > inner-capture > btn-capture-listener > btn-bubble-listener > inner-bubble > outer-bubble > document-bubble. The path continues above the document to the window object, which the script does not instrument.\n\nHow to change the order\n\nGoal | Technique\n\nRun a parent's handler before the child's | Register the parent with capture: true\nStop the event before it reaches deeper elements | stopPropagation() in a capture listener: the second line shows the event dying at inner-capture-stop, so neither button listener nor any bubble listener runs\nStop ancestors from hearing a click in the bubble phase | stopPropagation() in the button's bubble listener: the third line shows every capture listener had already fired, and inner-bubble, outer-bubble, document-bubble never do\nStop other listeners on the same element | stopImmediatePropagation(). Plain stopPropagation() does not: MDN notes it does not prevent propagation to other handlers on the current element\nReorder listeners on one element in one phase | They run in registration order. Remove and re-add to move one to the end\n\nEvent phases by name: capturing (1 in event.eventPhase), at target (2), bubbling (3).\n\nPitfalls\n\nstopPropagation() in a bubble handler hides the event from everything above, including analytics or a document-level delegation listener (a single listener on a parent that serves many children, which relies on events bubbling up to it). If a document-level listener must always see events, register it with capture: true: it fires on the way down, before any child can stop the event, as document-capture does in the third line.\nstopPropagation() does not cancel the browser's default action (following a link, submitting a form). That is preventDefault()'s job.\nEvents that do not bubble (focus, blur, mouseenter) still go through the capture phase, which is how a parent can observe them.\n\nRunning the code\n\nmkdir demo && cd demo\necho '{\"type\":\"module\"}' > package.json # save the listing as propagation_order.mjs here\ndocker run --rm -v \"$PWD\":/w -w /w mcr.microsoft.com/playwright:v1.48.2-jammy \\\n sh -c 'npm i playwright@1.48.2 && node propagation_order.mjs'\n\nThe image ships Chromium, Firefox and WebKit, so one run covers all three. The listing ends with assert calls, so a browser that disagrees makes the script exit with an error."}},{"@type":"Question","name":"A SPA takes about two seconds to become interactive on low-end phones and feels janky. Plan how you would profile it, what you would measure, and what you would fix first.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nStart by turning \"about two seconds to become interactive and janky\" into three measurable things: how soon the main content shows (LCP, Largest Contentful Paint, the time the biggest visible element appears), how soon the page responds to a tap (INP, Interaction to Next Paint, and in the lab TBT, Total Blocking Time, the time the main thread, the single thread that runs JavaScript, style and layout and responds to taps, spends blocked beyond 50 ms per task), and whether it moves around (CLS, Cumulative Layout Shift). Get field numbers for the real phones first, reproduce them in a lab with the CPU slowed, attribute main-thread time to whoever owns it (your bundle, a framework, a vendor script), and fix in order of metric moved per hour of effort. For a landing page with a hero image and third-party analytics that order is usually: make the hero image discoverable in the HTML, stop the vendor script from running as one block at startup, and only then cut your own startup JavaScript.\n\nStep 1: define the target, not \"TTI\"\n\nweb.dev says Time to Interactive (TTI) \"was removed as a metric from Lighthouse 10\", that it \"has proved overly sensitive to outlier network requests and long tasks\", and that LCP, TBT and INP \"are usually better metrics to use in place of TTI\". Use those. The thresholds web.dev gives for a good experience are LCP within 2.5 seconds, INP of 200 milliseconds or less, and CLS of 0.1 or less, judged at the 75th percentile of page loads (the value 75% of loads are at or better than).\n\nStep 2: profile in this order\n\n1. Field first. From real-user monitoring (RUM, measurement in visitors' own browsers), split LCP, INP and CLS by device class and by page. This says which metric is actually failing for the phones in question. A page that fails LCP and passes INP needs a different fix from the reverse.\n2. Lab reproduction. Same build, a fixed CPU slowdown, the same network profile, a fresh browser each run, 10 or more runs per variant, medians with their range. A single run is an anecdote.\n3. Trace the load. Read the long tasks (any main-thread task over 50 ms) and the long animation frames (frames that took over 50 ms to produce, the browser reports which scripts ran inside them), which list the scripts that ran in them with their source URLs. Group the time by owner: first-party app, framework, third party. The long task and long animation frame observers are limited-availability Chromium features (long animation frames shipped in Chrome and Edge 123 and later and are not supported in Firefox or Safari), so this attribution, and the harness below, describe Chromium; in other browsers use the browser's own profiler.\n4. Check the critical path of the largest element (the chain of requests that must finish before it can paint). When does the browser first learn about the hero image? If the image tag is created by JavaScript, the image request cannot start until that script has downloaded and run.\n5. Check layout stability (images without dimensions, late-injected banners).\n\nMeasured on a scaled-down landing page\n\nThe question is about feeling janky, which is INP's territory, but the harness does not simulate taps. It uses blocking time as the lab stand-in: a long task is exactly what makes a tap wait, so less blocking time means fewer and shorter waits. The harness below builds a page like the one in the question: an empty shell whose script renders a hero image and a button, plus a heavy third-party analytics script. It runs in Chromium with the CPU slowed 4x and a fixed emulated request latency, and applies the fixes one after another, reporting LCP, blocking time and which script owns the slow-frame time. The analytics fix is split into a \"later only\" row and a \"sliced only\" row, so the table shows which half of it matters. The final check fails if the hero change does not cut LCP by 40%, if moving the one-block script later alone cuts blocking time, if slicing it does not, or if cutting startup work does not halve what is left.\n\nHow to read the harness: busy(n) is a stand-in for JavaScript work, a loop of n square roots that occupies the main thread. The hero picture is built from 4000 seeded random coloured squares and screenshotted as a JPEG, because a flat colour is too simple for the browser to count as the largest contentful paint. The page's async script (async means the script downloads in parallel and runs the moment it arrives, interrupting the HTML parser) is the baseline analytics tag; the later variants replace it with a script that waits for load and then for requestIdleCallback (a browser call that runs a function when the main thread has nothing else to do; Safari does not implement it, so the code falls back to setTimeout). The blocking column sums duration - 50 over every long task, the same definition web.dev gives for Total Blocking Time (here counted over the whole load, not only after first paint). script time in slow frames sums, over long animation frames, how long each script ran inside them, grouped by whether the script URL is app.js or the analytics tag.\n\nimport { chromium } from 'playwright';\n\nconst RUNS = 11, RATE = 4;\nconst busy = (n) => { let x = 0; for (let i = 0; i < ${n}; i++) { x += Math.sqrt(i) % 3; } window.__sink = x; };\n// A hero picture with real detail (seeded random blocks): a flat colour is too simple for the browser to count as LCP.\nconst heroJpeg = await (async () => {\n const b = await chromium.launch(); const p = await b.newPage({ viewport: { width: 800, height: 400 } });\n let seed = 42; const rnd = () => (seed = (seed * 1664525 + 1013904223) % 4294967296) / 4294967296;\n const blocks = Array.from({ length: 4000 }, () => ).join('');\n await p.setContent(${blocks});\n const img = await p.screenshot({ type: 'jpeg', quality: 80 }); await b.close(); return img;\n})();\nconst heroTag = (extra) => \"hero\";\n\n// First-party app script: startup work, then render the hero (unless the HTML already has it) and a button.\nconst appJs = (work) => `${busy(work)}\n if (!document.getElementById('hero')) document.getElementById('root').insertAdjacentHTML('afterbegin', '${heroTag('')}');\n const b = document.createElement('button'); b.textContent = 'Start'; document.getElementById('root').append(b);\n window.__appDone = true;`;\n// Third-party analytics: the same initialisation done in one block, or in 30 slices that yield between slices.\nconst analyticsBlock = ${busy(9_000_000)} window.__analyticsDone = true;;\nconst analyticsSliced = (function run(n) { ${busy(300_000)} if (n < 30) setTimeout(() => run(n + 1), 0); else window.__analyticsDone = true; })(1);;\nconst loadAnalyticsAfterIdle = ;\n\nconst sync = ;\nconst heroHtml =
${heroTag('')}
;\nconst variants = {\n '0 baseline': { html:
${sync}, work: 6_000_000, analytics: analyticsBlock },\n '1 hero in HTML': { html: ${heroHtml}${sync}, work: 6_000_000, analytics: analyticsBlock },\n '2a + analytics later only': { html: ${heroHtml}${loadAnalyticsAfterIdle}, work: 6_000_000, analytics: analyticsBlock },\n '2b + analytics sliced only': { html: ${heroHtml}${sync}, work: 6_000_000, analytics: analyticsSliced },\n '2 + sliced and later': { html: ${heroHtml}${loadAnalyticsAfterIdle}, work: 6_000_000, analytics: analyticsSliced },\n '3 + less startup work': { html: ${heroHtml}${loadAnalyticsAfterIdle}, work: 2_000_000, analytics: analyticsSliced },\n};\n\nasync function once(browser, v) {\n const ctx = await browser.newContext();\n const page = await ctx.newPage();\n const delay = (ms) => new Promise((r) => setTimeout(r, ms));\n await page.route('http://app.test/**', async (route) => {\n const p = new URL(route.request().url()).pathname;\n await delay(p === '/' ? 50 : 120); // emulated network latency, the same for every variant\n if (p === '/app.js') return route.fulfill({ contentType: 'text/javascript', body: appJs(v.work) });\n if (p === '/hero.jpg') return route.fulfill({ contentType: 'image/jpeg', body: heroJpeg });\n return route.fulfill({ contentType: 'text/html', body: ${v.html} });\n });\n await page.route('http://cdn.analytics.test/**', async (route) => { await delay(120); route.fulfill({ contentType: 'text/javascript', body: v.analytics }); });\n await page.addInitScript(() => {\n window.__m = { lcp: 0, blocking: 0, app: 0, analytics: 0 };\n new PerformanceObserver((l) => l.getEntries().forEach((e) => { window.__m.lcp = e.startTime; })).observe({ type: 'largest-contentful-paint', buffered: true });\n new PerformanceObserver((l) => l.getEntries().forEach((e) => { window.__m.blocking += Math.max(0, e.duration - 50); })).observe({ type: 'longtask', buffered: true });\n new PerformanceObserver((l) => l.getEntries().forEach((e) => e.scripts.forEach((s) => {\n if (s.sourceURL.includes('analytics')) window.__m.analytics += s.duration;\n else if (s.sourceURL.includes('app.js')) window.__m.app += s.duration;\n }))).observe({ type: 'long-animation-frame', buffered: true });\n });\n const cdp = await ctx.newCDPSession(page);\n await cdp.send('Emulation.setCPUThrottlingRate', { rate: RATE });\n await page.goto('http://app.test/', { waitUntil: 'load' });\n await page.waitForFunction(() => window.__appDone && window.__analyticsDone, undefined, { timeout: 30000 });\n await page.waitForTimeout(300); // let observer entries be delivered\n const m = await page.evaluate(() => window.__m);\n await ctx.close();\n return m;\n}\n\nconst median = (a) => [...a].sort((x, y) => x - y)[Math.floor(a.length / 2)];\nconst browser = await chromium.launch();\nconst res = {};\nconsole.log(CPU ${RATE}x, emulated latency, median of ${RUNS} runs, ms);\nfor (const [name, v] of Object.entries(variants)) {\n const runs = [];\n for (let i = 0; i < RUNS; i++) runs.push(await once(browser, v));\n const med = (k) => median(runs.map((r) => r[k]));\n res[name] = { lcp: med('lcp'), blocking: med('blocking'), app: med('app'), analytics: med('analytics') };\n const r = res[name];\n console.log(${name.padEnd(28)} LCP=${r.lcp.toFixed(0).padStart(4)} blocking=${r.blocking.toFixed(0).padStart(4)} script time in slow frames: app.js=${r.app.toFixed(0).padStart(4)} analytics=${r.analytics.toFixed(0).padStart(4)});\n}\nawait browser.close();\nconst R = (n) => res[Object.keys(res).find((k) => k.startsWith(n + ' '))];\nconst [r0, r1, r2a, r2b, r2, r3] = ['0', '1', '2a', '2b', '2', '3'].map(R);\nconst ok = r1.lcp < 0.6 * r0.lcp // hero in the HTML moves LCP\n && r2a.blocking > 0.8 * r1.blocking // moving the same one-block script later does not cut blocking time\n && r2b.blocking < 0.6 * r1.blocking // slicing it does\n && r2.blocking < 0.6 * r1.blocking && r2.analytics === 0\n && r3.blocking < 0.5 * r2.blocking; // less startup work cuts what is left\nconsole.log('each step improves the metric it targets by a clear margin:', ok);\nprocess.exit(ok ? 0 : 1);\n\nOne sample run (Playwright 1.48.2 container, Chromium; medians of 11 runs per variant, milliseconds). Across five full re-runs the blocking figures moved by about 10 ms either way and the LCP figures by a few milliseconds; the ordering and the gaps did not change:\n\nCPU 4x, emulated latency, median of 11 runs, ms\n0 baseline LCP= 655 blocking= 343 script time in slow frames: app.js= 175 analytics= 262\n1 hero in HTML LCP= 201 blocking= 334 script time in slow frames: app.js= 173 analytics= 262\n2a + analytics later only LCP= 203 blocking= 339 script time in slow frames: app.js= 176 analytics= 266\n2b + analytics sliced only LCP= 199 blocking= 125 script time in slow frames: app.js= 175 analytics= 0\n2 + sliced and later LCP= 198 blocking= 119 script time in slow frames: app.js= 169 analytics= 0\n3 + less startup work LCP= 203 blocking= 8 script time in slow frames: app.js= 58 analytics= 0\neach step improves the metric it targets by a clear margin: true\n\nThe table reads as a diagnosis:\n\nStep 1, hero in the HTML. LCP fell by about two thirds (655 to 201 ms) while blocking time barely changed. The picture no longer waits for the app script to run before its request starts. The change is a few lines of markup. Two further hints were tried on this page and moved nothing: defer on the app script (the script downloads in parallel and runs after the HTML is parsed) and fetchpriority=\"high\" on the hero (a hint that asks the browser to fetch the image ahead of resources it would otherwise rank equal). With both added, step 1 measured the same LCP to within a few milliseconds, because the parser finds the image tag either way and nothing else competes with it. They matter when the image is found late or shares the link with other early requests, which this page does not reproduce; the measured gain here is discoverability.\nStep 2, the analytics script. Two halves, shown separately. Loading the same one-block script later (row 2a, after load and idle) left blocking time where it was, 339 ms against 334, because the block still runs as one long task, just later. Slicing it into small pieces (rows 2b and 2) took the vendor script's share of slow-frame time to zero and blocking time from about 335 to about 120 ms. The delay is what keeps the script from competing with the first view's requests, which this table does not measure; the slicing is what lets a tap in. In the stand-in, the script's own initialisation is what gets sliced, which looks like this in outline (30 slices of work, each followed by setTimeout(next, 0) so the browser can handle a tap between slices):\n\n(function run(n) { doSliceOfWork(); if (n < 30) setTimeout(() => run(n + 1), 0); })(1);\n\nFor a real vendor script you cannot edit, the same effect comes from loading it later (after load, after the first interaction), from a tag manager's delay setting (a tag manager is a service that loads vendor scripts on your behalf), or from running it off the main thread. Those options move the work; only slicing or moving it off the main thread shortens the long task itself.\nStep 3, less first-party startup work. In the stand-in the app's startup loop is cut to a third, standing in for code splitting and deferring work the first screen does not need. Blocking time falls to near zero. This is the largest engineering effort, which is why it comes last.\n\nThe scale is a model: the work is a synthetic loop, the latency is injected, and the page has one script of each kind. It shows which levers move which metric and by how much relative to each other; it does not predict your production numbers.\n\nWhat to fix first\n\nRecommendation: the order above, because it follows metric moved per unit of effort on a page of this shape. Two things would reorder it. If field data shows INP failing and LCP passing, step 2 and step 3 come before the hero change. If the vendor script is contractually required at first paint, move to sliced initialisation or a facade (a lightweight placeholder that loads the heavy widget on first use), and measure what that costs in data completeness.\n\nPitfalls\n\nFixing the lab and not the field: confirm with the 75th percentile of real users after release.\nOptimising a metric that passes. Look at the field table before choosing.\nDeferring a vendor script moves the work, it does not remove it; if a user taps while it runs, that tap waits. That is why slicing matters more than delaying alone.\nReporting the average. Use medians for lab runs and the 75th percentile for field data.\n\nRunning the code\n\nmkdir landing-profile && cd landing-profile # save profile.mjs here\nnpm init -y && npm pkg set type=module && npm i playwright@1.48.2\nnode profile.mjs # in mcr.microsoft.com/playwright:v1.48.2-jammy"}},{"@type":"Question","name":"A teammate asks when something should be a prop and when it should be state. How do you explain the difference, and how do you decide in a concrete example such as a product card with a quantity stepper?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nProps are the inputs a parent passes to a component; the component reads them and never changes them. State is data a component remembers between renders and updates itself, usually in response to the user. A render is one call of the component's function: React runs it to work out the markup for the current props and state, and runs it again (a re-render) whenever the component's own state changes or its parent re-renders. React normally re-renders a component whenever its parent re-renders, even when the props are identical; wrapping the component in React.memo opts out when the props are unchanged. Without state, a function would forget everything between those calls. To decide which a value is, ask three questions in order: can it be computed from props or other state (then it is neither, just a variable)? Is it decided by the parent (then it is a prop)? Does it change because of something that happens inside this component and must survive re-renders (then it is state)? In a product card with a quantity stepper, the name, price and stock are props, the quantity is state, and the total is computed.\n\nHow to explain it to a teammate\n\nAn analogy that holds up: props are the arguments to a function, state is a variable the function remembers between calls. A parent passes ; the card cannot reassign name, it can only ask the parent for a different one through a callback prop like onAdd. If the card needed a different name, the parent would render it again with a new prop. Props are read-only because data flows one way, downward: if children could rewrite what their parent gave them, any component could change any other's inputs and nobody could trace why a value changed.\n\nDeciding for the product card\n\nValue | Source | Verdict\n\nname, priceCents, stock | Parent / data layer | Props\nonAdd | Parent decides what \"add\" does | Callback prop\nquantity | User clicks the stepper; nothing else computes it | State\ntotalCents | quantity * priceCents | Derived: compute in render, store nowhere\nStepper's displayed number and limits | Card passes them | Props of Stepper (it has no state)\n\nImplementation\n\nimport { useState } from 'react';\n\n// Stepper: no state of its own. The number it shows and the limits are props.\nexport function Stepper({ value, min, max, onChange }) {\n return (\n
\n \n {value}\n \n
\n );\n}\n\n// ProductCard: name, priceCents, stock and onAdd come from the parent (props).\n// quantity changes in response to the user and nothing else computes it, so it is state.\n// total is computed from props + state on each render, so it is neither.\nexport function ProductCard({ name, priceCents, stock, onAdd }) {\n const [quantity, setQuantity] = useState(1);\n const totalCents = quantity * priceCents;\n return (\n
\n

{name}

\n \n

{(totalCents / 100).toFixed(2)}

\n \n
\n );\n}\n\nThe stepper has no state: it shows the value it is given and calls onChange. The card keeps quantity and computes totalCents on each render.\n\nProof\n\nThe control stores the total in state instead:\n\nimport { useState } from 'react';\nimport { Stepper } from './ProductCard.jsx';\n\n// Negative control: the total is copied into state when the quantity changes.\nexport function StoredTotalCard({ name, priceCents, stock }) {\n const [quantity, setQuantity] = useState(1);\n const [totalCents, setTotalCents] = useState(priceCents);\n return (\n
\n

{name}

\n { setQuantity(q); setTotalCents(q * priceCents); }} />\n

{(totalCents / 100).toFixed(2)}

\n
\n );\n}\n\nimport { render, screen, fireEvent } from '@testing-library/react';\nimport { ProductCard } from './ProductCard.jsx';\nimport { StoredTotalCard } from './StoredTotalCard.jsx';\n\nconst total = () => screen.getByTestId('total').textContent;\nconst qty = () => screen.getByLabelText('quantity').textContent;\nconst inc = () => fireEvent.click(screen.getByLabelText('increase'));\n\ntest('quantity is state: it changes on click and is clamped by the stock prop', () => {\n render( {}} />);\n expect(qty()).toBe('1');\n inc(); inc();\n expect(qty()).toBe('3');\n expect(screen.getByLabelText('increase').disabled).toBe(true);\n fireEvent.click(screen.getByLabelText('decrease'));\n expect(qty()).toBe('2');\n});\n\ntest('total is derived: it follows the price prop without any syncing code', () => {\n const { rerender } = render( {}} />);\n inc(); inc();\n expect(total()).toBe('37.50');\n rerender( {}} />); // parent changes a prop\n expect(total()).toBe('30.00');\n expect(qty()).toBe('3'); // state survives a prop change\n});\n\ntest('negative control: a total stored in state goes stale when the price prop changes', () => {\n const { rerender } = render();\n inc(); inc();\n rerender();\n expect(total()).toBe('37.50'); // 3 x 10.00 should be 30.00\n});\n\ntest('the callback prop reports state upward; the parent never reaches in', () => {\n const added = [];\n render( added.push(x)} />);\n inc();\n fireEvent.click(screen.getByText('Add to cart'));\n expect(added).toEqual([{ name: 'Mug', quantity: 2 }]);\n});\n\ntest('props are read-only: this React 18.3.1 development build freezes the props object', () => {\n let seen;\n const Probe = (props) => { seen = props; return null; };\n render();\n expect(Object.isFrozen(seen)).toBe(true);\n expect(() => { seen.name = 'Cup'; }).toThrow(TypeError);\n expect(seen.name).toBe('Mug');\n});\n\nRun with the setup below and the command npx vitest run propstate --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion' (the grep keeps only the result lines), the output is:\n\n ✓ propstate/propstate.test.jsx > quantity is state: it changes on click and is clamped by the stock prop\n ✓ propstate/propstate.test.jsx > total is derived: it follows the price prop without any syncing code\n ✓ propstate/propstate.test.jsx > negative control: a total stored in state goes stale when the price prop changes\n ✓ propstate/propstate.test.jsx > the callback prop reports state upward; the parent never reaches in\n ✓ propstate/propstate.test.jsx > props are read-only: this React 18.3.1 development build freezes the props object\n Tests 5 passed (5)\n\nThe tests show: quantity changes on click and is capped by the stock prop; when the parent re-renders the card with a new priceCents, the total follows (3 x 10.00 is 30.00) with the quantity kept; the stored-total control still shows 37.50 after the same price change; onAdd receives { name, quantity }; and in this React 18.3.1 development build the props object is frozen, so assigning to a prop throws a TypeError. A mutation check temporarily breaks the real code and confirms a test notices. Storing the total in the real card's state (sed -i 's/const totalCents = quantity \\ priceCents;/const [totalCents, setTotalCents] = useState(priceCents);/;s/onChange={setQuantity}/onChange={(q) => { setQuantity(q); setTotalCents(q priceCents); }}/' propstate/ProductCard.jsx) fails the derived-total test, because the total stays at 37.50 after the price prop drops to 10.00:\n\n ✓ propstate/propstate.test.jsx > quantity is state: it changes on click and is clamped by the stock prop\n × propstate/propstate.test.jsx > total is derived: it follows the price prop without any syncing code\n ✓ propstate/propstate.test.jsx > negative control: a total stored in state goes stale when the price prop changes\n ✓ propstate/propstate.test.jsx > the callback prop reports state upward; the parent never reaches in\n ✓ propstate/propstate.test.jsx > props are read-only: this React 18.3.1 development build freezes the props object\n⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯\nAssertionError: expected '37.50' to be '30.00' // Object.is equality\n Tests 1 failed | 4 passed (5)\n\nWhen state has to move\n\nIf something else on the page also needs the quantity (a cart summary, a sticky \"buy\" bar), keep it out of the card: move the state to the closest component that contains both users, and pass it down as a quantity prop with an onQuantityChange callback. That is \"lifting state up\", and it is the same shape the Stepper already has: a controlled component, one whose current value comes in as a prop and whose changes are reported through a callback instead of being kept inside. Doing it before a second reader exists adds props without a benefit.\n\nPitfalls\n\nCopying a prop into state (useState(props.price)) creates a second source of truth that stops following the prop after the first render, which is what the stored-total control shows.\nState that can be computed (totals, filtered lists, \"is empty\") is the most common over-use of state; compute it in render.\nMutating props or state objects in place hides changes from React and breaks one-way flow; the frozen props above are the guard rail for props, state needs the discipline of making new objects.\nState that should be in the URL (selected size, sort order) belongs in the router if links must reproduce it.\n\nRunning the code\n\nfiles in demo/propstate/: ProductCard.jsx (Implementation block), StoredTotalCard.jsx (first Proof block), propstate.test.jsx (second Proof block)\nnpm init -y && npm pkg set type=module\nnpm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16.0.1 @testing-library/dom@10.4.0 jsdom@25.0.1 vitest@2.1.4\nvitest.config.js:\nimport { defineConfig } from 'vitest/config';\nexport default defineConfig({ esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom', globals: true } });\nnpx vitest run propstate --reporter=verbose 2>&1 | grep -E '^ (✓|×)|Tests |Assertion'\n\nRun in a node:22 container (Node 22.23.3)."}},{"@type":"Question","name":"You need to deduplicate a large collection of records (browser strings, files by content, or database rows) by a natural key, deciding which structure keeps the check fast without blowing up memory. Separately: given a stream of values, detect whether any value repeats within a bounded distance k of its earlier occurrence, without keeping the entire history.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\nFor deduplicating a large collection by a natural key or content hash, a hash set of keys already seen gives O(1) expected membership checks at the cost of O(u) memory for u unique keys, the right default unless memory itself is the binding constraint (then sort-and-scan trades CPU for lower peak memory). The separate streaming question, detecting a repeat within a bounded distance k, needs no history at all: keep only a sliding window of the last k values in a bounded hash set, evicting the oldest as you go, and check membership before inserting each new value.\n\nStructured elaboration\nLarge-collection dedup by natural key or content hash (folding both framings as the same hashing-for-membership idea):\nA hash set of keys: O(n) expected time, O(u) space where u is the number of unique keys; the default choice unless u is close to n (fine, no real savings anyway) or genuinely too large to fit in memory.\nSort-then-scan: O(n log n) time, but only needs O(1) extra memory beyond the sort itself, since each element only has to be compared to its immediate predecessor once sorted; useful when a full hash set can't fit but an external or in-place sort can.\nContent-hash file dedup and natural-key row dedup are the SAME mechanism (hashing for membership) applied to a different notion of identity: a natural key models domain identity (e.g. the same customer id across two records), while a content hash models byte-for-byte identity (the same file regardless of name or path). Don't conflate the two: two rows can legitimately share a natural key while differing in content (an update to the same record), which content-hashing would incorrectly treat as two distinct items.\n\nBounded-distance repeat detection in a stream: maintain a fixed-size sliding window (a deque of the last k values) plus a parallel hash set holding exactly those same values, for O(1) membership tests. On each new value: check the set first (a hit means a repeat within distance k); insert the value; if the window now holds more than k elements, evict and remove the oldest, being careful that a value with multiple copies still in the window is only removed from the set once its LAST remaining copy leaves.\n\nfrom collections import deque\n\ndef dedupe_by_key(records, key_fn):\n \"\"\"\n Natural-key / content-hash dedupe: O(n) expected time, O(u) space\n where u = number of unique keys. Keeps the first record seen per key.\n \"\"\"\n seen = set()\n unique = []\n for r in records:\n k = key_fn(r)\n if k not in seen:\n seen.add(k)\n unique.append(r)\n return unique\n\ndef has_nearby_duplicate(stream, k):\n \"\"\"\n True if any value repeats within distance k of an earlier occurrence.\n Keeps only the last k elements in memory: O(1) amortized (averaged over a\n sequence of operations) per step, O(k) space, instead of O(n) for keeping the full history.\n \"\"\"\n window = deque()\n window_set = set()\n\n for v in stream:\n if v in window_set:\n return True\n window.append(v)\n window_set.add(v)\n if len(window) > k:\n oldest = window.popleft()\n if oldest not in window: # a duplicate copy may still be present\n window_set.discard(oldest)\n return False\n\nrecords = [\n {\"id\": 1, \"name\": \"a\"},\n {\"id\": 2, \"name\": \"b\"},\n {\"id\": 1, \"name\": \"a-dup\"},\n {\"id\": 3, \"name\": \"c\"},\n]\nprint(dedupe_by_key(records, key_fn=lambda r: r[\"id\"]))\n\nprint(has_nearby_duplicate([1, 2, 3, 1], k=3)) # distance 3, k=3 -> True\nprint(has_nearby_duplicate([1, 2, 3, 1], k=2)) # distance 3, k=2 -> False\n\nOutput:\n[{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]\nTrue\nFalse\n\nWorked example\ndedupe_by_key keeps the first record for each id and discards the later duplicate with id 1, exactly as shown above. For the streaming check, the value 1 repeats at indices 0 and 3, a distance of 3: with k=3 that's within the allowed window (True), but with k=2 the same repeat is now too far apart to count (False), matching the printed output.\n\nComplexity\n\ndedupe_by_key: expected time for input records ( expected hash-set\noperations each), space for unique keys. has_nearby_duplicate: \nexpected time overall ( amortized per stream value), space for the bounded\nwindow and its parallel set.\n\nEdge cases\n\nEmpty input: dedupe_by_key([], ...) returns []; has_nearby_duplicate([], k) returns\n False immediately, since the loop body never runs.\nk=0: the membership check happens before insertion, so a value is compared against\n window_set before it is ever added; since len(window) > 0 is true right after that single\n insertion, the value is immediately evicted again, meaning no two values are ever in the\n window at once and no repeat, not even an adjacent one, is ever detected.\nDuplicate values still live in the window: the if oldest not in window check before\n discarding from window_set means a value with more than one copy currently in the window\n stays correctly counted until its LAST remaining copy leaves.\nAll-unique records: dedupe_by_key returns the full input list unchanged, in the same\n order.\nAll-same key: dedupe_by_key returns just the single first record seen for that key.\n\nTrade-offs & pitfalls\n \n\nUnbounded memory pitfall: a plain hash set remembers every unique value ever seen; for an unbounded, mostly-non-repeating stream in a long-running service, that is an unbounded memory leak. The k-bounded window exists precisely to cap memory at O(k), at the cost of only detecting repeats within that horizon, not globally.\nHash collisions are not a correctness issue inside a language-level hash set (which resolves them internally), but ARE a correctness issue when a hash itself represents identity, as in content-hash dedup: a collision between two different files would wrongly treat them as duplicates. A cryptographic hash makes this astronomically unlikely, but \"verify byte-equality, don't trust the hash alone\" is the safer default whenever the cost of a false match is high, such as deleting what you believe is a duplicate file.\nApproximate structures (a Bloom filter, or HyperLogLog for cardinality) can shrink memory further, but trade away exactness: a Bloom filter can report \"possibly seen\" for something genuinely new, and HyperLogLog gives an approximate count, not membership. Reach for these only after an exact hash set has been ruled out on memory grounds.\nNatural-key vs content-hash mismatch: applying a content-hash approach where the problem actually wants natural-key identity (or vice versa) silently changes what counts as \"the same record,\" which is easy to get wrong without stating the identity definition up front."}},{"@type":"Question","name":"Type a component's props so that it is either a link or a button but never both: link props allow href and forbid onClick, and button props do the reverse. Provide the types and a usage that type-checks plus one that must fail.","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nModel the two shapes as separate object types, give each one the other's forbidden property as ?: never, and make the props a union of the two (LinkProps | ButtonProps). A union means \"exactly one of these shapes\", and ?: never means \"this key may not be given a value\", so supplying both href and onClick matches neither member and fails to compile.\n\n// action.ts\nexport type LinkProps = { label: string; href: string; onClick?: never };\nexport type ButtonProps = { label: string; onClick: () => void; href?: never };\nexport type ActionProps = LinkProps | ButtonProps;\n\nexport function action(props: ActionProps): string {\n if (props.href !== undefined) {\n return ${props.label};\n }\n props.onClick();\n return ;\n}\n\nA UI component declares props: ActionProps the same way; a plain function stands in for the component here so the output is easy to reproduce.\n\nUsage that type-checks, one variant each\n\n// usage_ok.ts\nimport { action } from \"./action\";\n\nconsole.log(action({ label: \"Pricing\", href: \"/pricing\" }));\nconsole.log(action({ label: \"Save\", onClick: () => console.log(\"saved\") }));\n\nCompiled with tsc --strict and run with Node, this prints:\n\nPricing\nsaved\n\n\n(saved appears before the button markup because the handler runs inside action before it returns the string, and console.log prints the return value afterwards.)\n\nUsage that must fail\n\n// usage_bad.ts\nimport { action } from \"./action\";\n\naction({ label: \"Both\", href: \"/x\", onClick: () => {} });\naction({ label: \"Neither\" });\naction({ label: \"Bad\", onClick: \"go\" });\n\ntsc --strict --noEmit (TypeScript 5.9.3) reports:\n\nusage_bad.ts(4,8): error TS2345: Argument of type '{ label: string; href: string; onClick: () => void; }' is not assignable to parameter of type 'ActionProps'.\n Types of property 'onClick' are incompatible.\n Type '() => void' is not assignable to type 'undefined'.\nusage_bad.ts(5,8): error TS2345: Argument of type '{ label: string; }' is not assignable to parameter of type 'ActionProps'.\n Property 'onClick' is missing in type '{ label: string; }' but required in type 'ButtonProps'.\nusage_bad.ts(6,24): error TS2322: Type 'string' is not assignable to type '() => void'.\n\nWhy it works\n\n1. href?: never rather than omitting href. An object literal with an extra property is rejected only when it is checked against a single type (excess property checking). Against a union, a literal is allowed to carry a property that exists in any member, so without onClick?: never on the link, { href, onClick } would be accepted as a LinkProps with a stray key. Declaring the forbidden key as optional never makes the only legal value undefined, which is why the first error reads '() => void' is not assignable to type 'undefined'.\n2. Narrowing inside the component. Narrowing means the compiler uses a check in the code (an if, a typeof, a comparison) to treat a value as a more specific type inside that branch. The textbook discriminated union has a literal tag such as kind: \"link\" in every member, and checking the tag narrows. TypeScript also treats a shared property as a discriminant when at least one member gives it a singleton type such as a string literal, null or undefined (documented in the TypeScript 3.2 release notes). Here the shared property is href, whose type is string in one member and undefined in the other, so props.href !== undefined narrows to LinkProps, and the printed run shows it compiles. In the fall-through, props.onClick is a callable () => void with no non-null assertion (the ! suffix, as in props.onClick!(), which tells the compiler to treat a value as non-null without any check). An explicit tag such as kind: \"link\" | \"button\" also works and reads more clearly, at the cost of making callers pass the tag.\n3. Third error. onClick: \"go\" is not a function, and the compiler reports it against the onClick property itself.\n\nTrade-offs and pitfalls\n\nTypes are erased at compile time. A caller using any, a JSON payload, or plain JavaScript can pass both props at runtime, so a component whose misuse would be harmful should also check at runtime.\nonClick?: never accepts an explicit onClick: undefined (unless exactOptionalPropertyTypes is on: a compiler flag that makes an optional property mean \"absent or the declared type\", so writing undefined into it is an error unless the type includes undefined). That is harmless here because the branch tests href.\nKeep strict on. The listings above were compiled with it. With strict off the same bad call is still rejected, but the first error then names ButtonProps and the type never instead of undefined, so the messages shown here would not match.\nFor more than two variants, derive the \"forbid the rest\" keys with a helper instead of hand-writing every ?: never, but only once there are enough variants to justify the extra type machinery.\n\nRunning the code\n\nnpm i typescript@5\nnpx tsc --strict --module commonjs --target es2022 --outDir out action.ts usage_ok.ts\nnode out/usage_ok.js\nnpx tsc --strict --noEmit --module commonjs --target es2022 action.ts usage_bad.ts"}},{"@type":"Question","name":"Two senior frontend engineers disagree about a team-wide approach to component composition and mentoring juniors. You are the technical lead. Describe how you would resolve the conflict, ensure juniors get consistent guidance, and incorporate the best parts of both viewpoints into a teachable standard and onboarding materials. Include concrete examples and measurable outcomes where relevant.","acceptedAnswer":{"@type":"Answer","text":"Situation & goal\nTwo senior frontend engineers disagree on component composition (e.g., container-presentational vs. hooks-driven composition) and how juniors should be mentored. As technical lead I need to resolve conflict, create consistent guidance for juniors, and capture best of both views into a teachable standard and onboarding materials.\n\nAction plan\n1. Facilitate a focused, timeboxed design discussion\nAsk each senior to present pros/cons with concrete examples (small demo repo or 10–15 minute walkthrough).\nCapture trade-offs: reusability, testability, bundle size, mental model for juniors.\n2. Align on objective criteria\nDefine measurable decision factors: bundle impact (< +2 KB), average unit test coverage (> 80%), render performance (no noticeable jank in 95th percentile), and developer onboarding time.\n3. Prototype and measure\nImplement two small sample components (one for each approach) in a feature branch with docs and tests.\nRun simple metrics: bundle size (webpack), test coverage, and a quick dev survey (5 devs including 2 juniors) for understandability.\n4. Synthesize a hybrid standard\nKeep strengths from both approaches (e.g., use hook-based composition for shared logic + explicit presentational props for clarity).\nProduce a concise pattern guide: when to use hooks, when to split container/presentational, naming conventions, prop vs. context rules.\n5. Make it teachable and enforceable\nCreate onboarding materials: checklist, example repo, 1-hour recorded walkthrough, and a 2-week mentor pairing plan.\nAdd PR template and linter/ESLint rules to catch anti-patterns.\n6. Coaching & feedback loop\nPair juniors with alternating mentors from both seniors for first 2 sprints.\nRun weekly office hours and monthly retro to adjust the standard.\n\nConcrete example\nStandard: \"Use hooks for local logic and reusable behavior; split purely presentational component when markup > 50 lines or props > 6.\"\nOnboarding: 1-hour workshop + 3 guided PRs in first sprint.\n\nMeasurable outcomes\nReduce onboarding time by 30% (measured by time to first approved component PR).\nAchieve 90% adherence in first 8 weeks (via automated lint + quarterly audits).\nIncrease junior confidence (pre/post survey) by 40%.\n\nResult & learning\nThis approach resolves the conflict through evidence, yields a practical hybrid standard, ensures juniors receive consistent, measurable guidance, and keeps both seniors engaged by adopting their best ideas."}},{"@type":"Question","name":"Playwright supports multiple browsers. Describe a cross-browser testing strategy with it that minimises duplicate tests while still covering browser-specific behaviour. How do you parameterise tests and manage browser-specific fixtures or capabilities?","acceptedAnswer":{"@type":"Answer","text":"Direct answer\n\nWrite each test once, in one set of files, and let Playwright projects decide where it runs. A project is a named configuration (here one per browser engine) that runs the suite with its own settings. Chromium runs everything; Firefox and WebKit run only the tests tagged as engine-sensitive, because app logic that does not touch the browser engine gives the same answer everywhere. Handle browser differences by feature detection inside a fixture (a fixture is a reusable setup value a test asks for by name), and reserve per-browser branches for the few cases where the difference is the thing under test.\n\nProjects and tags decide where a test runs\n\n// playwright.config.ts\nimport { defineConfig, devices } from '@playwright/test';\n\n// Chromium runs every test. Firefox and WebKit run only tests tagged @engine,\n// the ones whose result depends on the browser engine rather than app logic.\nconst engineOnly = /@engine/;\n\nexport default defineConfig({\n testDir: './tests',\n fullyParallel: true,\n reporter: 'list',\n projects: [\n { name: 'chromium', use: { ...devices['Desktop Chrome'] } },\n { name: 'firefox', use: { ...devices['Desktop Firefox'] }, grep: engineOnly },\n { name: 'webkit', use: { ...devices['Desktop Safari'] }, grep: engineOnly },\n ],\n});\n\nNo duplicated tests. The same tests/ directory feeds all three projects. A device descriptor such as devices['Desktop Firefox'] is a ready-made bundle of settings (viewport size, user agent, touch support) that makes a project behave like that device. Tests are not copied per browser.\nEngine-sensitive means layout, form controls, storage, input handling, media and any API that engines implement separately. Pure logic (price formatting, reducers) is tagged @logic and runs on Chromium only.\nPer-project filters. grep on a project limits that project to matching tests. A command-line --grep is applied on top: with this config, --project=firefox --grep \"@logic\" lists 0 tests and --project=chromium --grep \"@logic\" lists 1.\nBrowser-specific capabilities live in the project's use block, for example a branded Edge build with channel: 'msedge' (documented for projects), a mobile project built from a device descriptor with touch enabled, or a different baseURL per environment. Keep these out of test bodies.\n\nFixtures: detect features, do not sniff browsers\n\n// tests/fixtures.ts\nimport { test as base } from '@playwright/test';\n\ntype Caps = { hasDialog: boolean; hasContainerQueries: boolean };\n\n// Feature detection in the page under test, never a check of browserName for logic.\nexport const test = base.extend<{ caps: Caps }>({\n caps: async ({ page }, use) => {\n await page.setContent('

probe

');\n const caps = await page.evaluate(() => ({\n hasDialog: typeof HTMLDialogElement === 'function',\n hasContainerQueries: CSS.supports('container-type: inline-size'),\n }));\n await use(caps);\n },\n});\nexport { expect } from '@playwright/test';\n\nA fixture runs the probe inside the page under test, so a test says \"skip when the page cannot do this\" and the reason is the missing feature, not the browser's name. A skip keyed on browserName goes stale when an engine ships the feature; a skip keyed on CSS.supports or typeof HTMLDialogElement heals itself. Keep a skip report in CI so a feature that silently disappears from every engine does not turn the whole row into a skip.\n\nParameterised tests\n\n// tests/cart.spec.ts\nimport { test, expect } from './fixtures';\n\nconst money = (cents: number) => $${(cents / 100).toFixed(2)};\n\ntest('@logic totals format as dollars', () => {\n expect(money(1999)).toBe('$19.99');\n});\n\n// Assigning an impossible calendar date to a date input must leave it empty.\nfor (const [value, expected] of [['2026-02-29', ''], ['2026-02-28', '2026-02-28']]) {\n test(@engine date input sanitises ${value}, async ({ page }) => {\n await page.setContent('');\n await page.$eval('#d', (el: HTMLInputElement, v) => { el.value = v; }, value);\n expect(await page.inputValue('#d')).toBe(expected);\n });\n}\n\ntest('@engine dialog opens modally when supported', async ({ page, caps }) => {\n test.skip(!caps.hasDialog, 'no in this engine');\n await page.setContent('hi');\n await page.$eval('#m', (d: HTMLDialogElement) => d.showModal());\n expect(await page.$eval('#m', (d: HTMLDialogElement) => d.open)).toBe(true);\n});\n\ntest('@engine container query narrows the card', async ({ page, caps }) => {\n test.skip(!caps.hasContainerQueries, 'container queries unsupported');\n await page.setContent(`
x
`);\n expect(await page.$eval('#c', (e) => e.getBoundingClientRect().width)).toBe(150);\n});\n\nReading the three listings line by line: in the fixture, base.extend<{ caps: Caps }> declares a new fixture called caps; the code before await use(caps) is setup, the value passed to use is what the test receives, and anything after it would run as teardown. page.evaluate runs the probe inside the browser page and returns the results. In the spec, page.$eval('#d', fn, value) runs fn inside the page on the first element matching #d, with value passed as its second argument, here assigning it to the date input. 2026-02-29 must give '' because 2026 is not a leap year, so that date does not exist and the browser sanitises the assigned value to an empty string. is the HTML element for a dialog box, and showModal() opens it modally, meaning the rest of the page is blocked while it is open. test.skip(!caps.hasDialog, reason) ends the test as skipped when the probe found no support. In the container-query test, #w is a 300px-wide container, and the rule @container (max-width:400px) applies when that container is at most 400px wide, so #c becomes 50% of its container's width: 300 x 0.5 = 150.\n\nThe for loop over [value, expected] pairs generates one test per data row, so the date-input check is written once and runs twice per engine. The same loop can take a list of viewports or locales.\n\nRun it\n\nRun in the Playwright 1.48.2 image (Chromium 130, Firefox 131, WebKit 18.0, Linux), the per-project test counts were:\n\nchromium: Total: 5 tests in 1 file\nfirefox: Total: 4 tests in 1 file\nwebkit: Total: 4 tests in 1 file\n\nnpx playwright test then printed 13 passed (5 + 4 + 4), and npx playwright test --repeat-each=10 printed 130 passed, with no failures or skips across those repeats. Running everything on every engine would be 5 x 3 = 15 executions; the tag split saves 2 here.\n\nWhy this scales\n\nWith the suite sizes of a real product the saving is larger. For 200 tests of which 60 are engine-sensitive, the split runs 140 + 60 x 3 = 320 executions against 200 x 3 = 600 for everything everywhere, which is 46.7 percent fewer.\n\nTrade-offs and pitfalls\n\nMis-tagging. A test that depends on the engine but carries @logic never runs on Firefox or WebKit. Review the tag in code review, and when a bug escapes on a non-Chromium browser, add the tag to the test that should have caught it.\nPlaywright WebKit is not Safari. It tracks WebKit main and runs on Linux here, so it cannot show iOS-specific behaviour (touch handling, on-screen keyboard, iOS storage rules). Keep a real-device row for those.\nDo not hide real divergence. If a behaviour is meant to differ per browser, test the expected difference with an explicit per-browser assertion and a comment saying why; do not skip.\n\nRunning the code\n\nin an empty directory with package.json {\"type\":\"module\",\"devDependencies\":{\"@playwright/test\":\"1.48.2\"}}\nfiles: playwright.config.ts, tests/fixtures.ts, tests/cart.spec.ts (as above)\ndocker run --rm --ulimit core=0 -v \"$PWD\":/src:ro \\\n mcr.microsoft.com/playwright:v1.48.2-jammy sh -c \\\n 'cp -r /src /w && cd /w && npm i @playwright/test@1.48.2 && \\\n npx playwright test --project=firefox --list && \\\n npx playwright test && npx playwright test --repeat-each=10'"}}]}

Junior Frontend Developer Interview Preparation Guide for Spotify

Frontend Developer
Spotify
Junior
5 rounds
Updated 6/18/2026

Spotify's interview process for junior frontend developers typically follows a multi-stage structure including an initial recruiter screening call, technical phone interviews, and a full-day onsite with multiple rounds covering coding, technical problem-solving, product design, and behavioral competencies. The process emphasizes practical frontend skills, understanding of web performance, component-based architecture (particularly React), and cultural fit with Spotify's engineering values. Total timeline typically spans 4-6 weeks from initial contact to offer.

Interview Rounds

1

Recruiter Screening

2

Technical Phone Screen

3

React and Component Development Interview

4

Web Performance and Technical Depth Interview

5

Behavioral and Culture Fit Interview

Frequently Asked Frontend Developer Interview Questions

Cross-Browser and Cross-Platform TestingHardTechnical
59 practiced

Login works in Chrome, but in our automated runs an embedded third-party widget and the sign-in flow break on Safari and Firefox. How can differences in cookie policy between browsers cause this, how would you write automated tests that validate cookie behaviour across browsers, and how would you configure test environments to cover both legacy and modern policies?

Proudest Achievements and Project PortfolioMediumBehavioral
54 practiced

What's a lesson from this project that changed how you approach your work since?

Frontend Fundamentals: HTML, CSS, and Responsive StylingMediumTechnical
74 practiced

You are reviewing a component library and find three recurring accessibility problems: clickable divs, icon-only buttons with no text, and focus that disappears when a panel opens. For each, show the markup fix and explain what a keyboard or screen-reader user experiences before and after.

DOM Manipulation and Browser APIsEasyTechnical
145 practiced

Take an outer div containing an inner div containing a button, with listeners on all three, some registered for capture and some for bubble. Describe the order they fire in and how you would change it.

Frontend Performance and Rendering OptimizationHardTechnical
64 practiced

A SPA takes about two seconds to become interactive on low-end phones and feels janky. Plan how you would profile it, what you would measure, and what you would fix first.

Frontend Component and State ArchitectureEasyTechnical
76 practiced

A teammate asks when something should be a prop and when it should be state. How do you explain the difference, and how do you decide in a concrete example such as a product card with a quantity stepper?

Algorithmic Problem-Solving and Data Structure SelectionMediumTechnical
54 practiced

You need to deduplicate a large collection of records (browser strings, files by content, or database rows) by a natural key, deciding which structure keeps the check fast without blowing up memory. Separately: given a stream of values, detect whether any value repeats within a bounded distance k of its earlier occurrence, without keeping the entire history.

JavaScript and TypeScript FundamentalsHardTechnical
56 practiced

Type a component's props so that it is either a link or a button but never both: link props allow href and forbid onClick, and button props do the reverse. Provide the types and a usage that type-checks plus one that must fail.

Growth Mindset and Learning AgilityHardTechnical
47 practiced

Two senior frontend engineers disagree about a team-wide approach to component composition and mentoring juniors. You are the technical lead. Describe how you would resolve the conflict, ensure juniors get consistent guidance, and incorporate the best parts of both viewpoints into a teachable standard and onboarding materials. Include concrete examples and measurable outcomes where relevant.

Cross-Browser and Cross-Platform TestingMediumTechnical
50 practiced

Playwright supports multiple browsers. Describe a cross-browser testing strategy with it that minimises duplicate tests while still covering browser-specific behaviour. How do you parameterise tests and manage browser-specific fixtures or capabilities?

Want to create your own tailored preparation guide using our deep research?

Get Started for Free

Interview-Ready Courses

Visual-first, interactive, structured learning paths

Browse Frontend Developer jobs

AI-enriched listings across hundreds of company career pages

Explore Jobs