← Interview prep

Frontend interview questions

Browser performance, accessibility, and frontend systems.

59 questions · Page 3 of 3

Want the full pack? Interview packs · Mock interview · Mentora

Page 3 of 3

Questions 41–59 of 59 · 0 of 19 on this page marked learned

41.frontend-0041Hardsenior

How do you build an accessible tabs widget with roles, roving tabindex and arrow key navigation?

Use role tablist, tab and tabpanel, link them with aria-controls and aria-labelledby, mark the active tab with aria-selected, keep only the active tab in the Tab order with tabindex, and move between tabs with the arrow keys, Home and End.

Full answer

The ARIA Authoring Practices describe a pattern that users of assistive technology expect. For tabs:

  • The container has role="tablist". Each tab is a button with role="tab". Each panel has role="tabpanel".
  • aria-selected="true" is on the active tab and false on the others. aria-controls on each tab points to its panel, and the panel has aria-labelledby pointing back to the tab.
  • Only the selected tab is in the page's Tab order (tabindex="0"), and the others have tabindex="-1". This is a roving tabindex. One Tab press enters the widget, and the next Tab press leaves it, so a long list of tabs does not trap the user.
  • Left and Right arrow keys move to the previous and next tab, and wrap around at the ends. Home and End go to the first and last tab. In the simple "automatic activation" model, focus and selection move together.
  • Inactive panels are hidden with the hidden attribute, which removes them from the tree and the layout.
  • The panel can take tabindex="0" when it has no focusable content, so keyboard users can reach it.

Do this only if you need custom tabs. If the content is a set of page links, use a nav list with links. For disclosure of a single section, details and summary are enough. A custom widget costs code and testing.

Common bugs: using aria-selected without updating it, hiding panels with CSS in a way that leaves them in the tree, forgetting to call focus() on the new tab, and leaving every tab at tabindex="0".

The test presses Tab to enter the widget, then ArrowRight, End, and ArrowLeft, and reads which tab has focus and which panel is visible. It then reads the Chrome accessibility snapshot to confirm the selected tab. No screen reader was run.

html
<div role="tablist" aria-label="Course sections" id="tabs">
  <button role="tab" id="t1" aria-controls="p1" aria-selected="true" tabindex="0">Overview</button>
  <button role="tab" id="t2" aria-controls="p2" aria-selected="false" tabindex="-1">Lessons</button>
  <button role="tab" id="t3" aria-controls="p3" aria-selected="false" tabindex="-1">Reviews</button>
</div>
<div role="tabpanel" id="p1" aria-labelledby="t1">About the course</div>
<div role="tabpanel" id="p2" aria-labelledby="t2" hidden>Lesson list</div>
<div role="tabpanel" id="p3" aria-labelledby="t3" hidden>Student reviews</div>
<script>
  const tabs = [...document.querySelectorAll('[role=tab]')];
  function select(i) {
    tabs.forEach((t, n) => {
      const on = n === i;
      t.setAttribute('aria-selected', on);
      t.tabIndex = on ? 0 : -1;
      document.getElementById(t.getAttribute('aria-controls')).hidden = !on;
    });
    tabs[i].focus();
  }
  tabs.forEach((t, i) => t.addEventListener('click', () => select(i)));
  document.getElementById('tabs').addEventListener('keydown', (e) => {
    const i = tabs.indexOf(document.activeElement);
    if (i < 0) return;
    const keys = { ArrowRight: (i + 1) % tabs.length, ArrowLeft: (i + tabs.length - 1) % tabs.length, Home: 0, End: tabs.length - 1 };
    if (e.key in keys) { e.preventDefault(); select(keys[e.key]); }
  });
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The check used real key presses (Tab, ArrowRight, End, ArrowLeft) and read the focused tab and visible panel. The accessibility snapshot showed the selected tab. No screen reader was run.

Key points

  • Roles: tablist, tab, tabpanel, linked by aria-controls and aria-labelledby.
  • aria-selected marks the active tab.
  • Roving tabindex: only the active tab is a Tab stop.
  • Arrow keys, Home and End move between tabs.
  • Hide inactive panels with the hidden attribute.

Common mistakes

  • Leaving all tabs at tabindex 0.
  • Switching the panel with a click handler only, with no key support.
  • Forgetting to update aria-selected.
  • Building custom tabs where a list of links would do.

Follow-ups

  • When should activation wait for Enter instead of following the arrow keys?
  • How would you support a vertical tablist?
  • How does this differ from an accordion?

Tips

  • Name the three roles and the roving tabindex idea first.
  • Say when not to build it.
42.frontend-0042Mediummid

How do you test accessibility automatically, and what can automated tools not tell you?

Run a rules engine such as axe-core in unit, end-to-end and CI tests to catch machine-checkable faults like missing names, bad ARIA and low contrast. It cannot judge whether alt text is meaningful, whether focus order makes sense or whether a flow is usable, so keyboard and screen reader checks by a person are still needed.

Full answer

Automated tools parse the page and apply rules. They are quick, cheap and good at regressions. They find faults such as:

  • images without alt, buttons and inputs without an accessible name;
  • invalid or misused ARIA, duplicate ids that ARIA relies on;
  • missing document language, missing page title;
  • insufficient colour contrast in many (not all) cases;
  • skipped heading levels in some tools, landmarks used wrongly.

They cannot decide:

  • whether alt="image" is helpful (it is present, so it passes);
  • whether the focus order matches the visual order and the reading order;
  • whether a custom widget can really be used with a keyboard and a screen reader;
  • whether error messages are clear, or whether time limits are fair;
  • whether captions are accurate, or colour is the only way to see a status.

Studies and vendors give different numbers for the share of problems that tools can catch, so do not quote a percentage. Say that automation covers a part and a manual check covers the rest.

A sensible process:

  1. Lint in the editor with an accessibility lint rule set.
  2. Run axe-core inside component or page tests, and fail the build on new violations.
  3. Run a scanner or Lighthouse in CI on key pages.
  4. Test by hand for every new widget: Tab through it, use it without a mouse, zoom to 200 percent, and try a screen reader.
  5. Keep known issues in a tracked list, not in a muted rule.

The snippet runs the axe-core engine on a deliberately bad page in Chrome, and returns the rule ids it found. The page has an image without alt, a button without a name, an input without a label and a page with no title. The test checks that these rules fire, and that the good version has none of them. The checks that axe skips for manual review were not run.

javascript
// In a browser test, after loading axe.min.js into the page:
const results = await axe.run(document, { runOnly: ['wcag2a', 'wcag2aa'] });
window.ruleIds = results.violations.map((v) => v.id).sort();

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The axe-core library was loaded into the page by the test, and the snippet body ran as shown. The bad page reported image-alt, button-name, label, document-title and html-has-lang, and the good page reported none of them. Checks that axe leaves for manual review were not run.

Key points

  • Rules engines catch machine-checkable faults and prevent regressions.
  • They cannot judge meaning, focus order or real usability.
  • Use them in editor, component tests and CI.
  • Add manual keyboard and screen reader checks.
  • Do not quote a single percentage of coverage.

Common mistakes

  • Treating a clean automated report as proof of accessibility.
  • Muting a failing rule instead of fixing it.
  • Testing only the home page.
  • Skipping keyboard testing because the scanner passed.

Follow-ups

  • Which kinds of faults need a human?
  • How would you add axe to a Playwright test?
  • How do you handle a violation in third-party code?

Tips

  • Give two examples of what tools catch and two of what they cannot.
  • Describe a layered process, not one tool.
43.frontend-0043Mediummid

What does a JavaScript bundler do, and why do front-end projects still use one when browsers support ES modules?

A bundler starts from an entry file, follows every import to build a module graph, transforms the code (TypeScript, JSX), removes unused code, minifies, splits it into chunks and writes hashed files. Native modules work without a bundler, but a bundle avoids hundreds of requests, enables tree shaking and handles non-JavaScript assets.

Full answer

A bundler turns many source files into a few files that the browser downloads. The main steps:

  1. Resolve. Starting at the entry point, it reads each import and finds the file, including packages in node_modules.
  2. Transform. Loaders convert TypeScript, JSX and modern syntax to what the target browsers run, and can import CSS, images and JSON.
  3. Build the module graph. Every file and its dependencies form a graph. The bundler knows which code is reachable.
  4. Optimise. It removes unused exports (tree shaking), merges modules, minifies names and whitespace, and can split the graph into chunks.
  5. Emit. It writes output files with content hashes in the names, and a manifest or HTML that points to them.

Why not just use native ES modules? They do work, and for small projects or fast local development they are fine. Reasons to bundle for production:

  • A page that imports a deep tree of modules makes a chain of requests, because the browser finds the next import only after it loads the previous file. Bundling reduces round trips. HTTP/2 helps, but it does not remove the discovery chain.
  • Packages are published in many formats, and a bundler normalises them.
  • Dead code removal, minification and chunking need to see the whole graph.
  • Non-JavaScript assets and environment variables need processing.

Popular tools are esbuild, Rollup, webpack, Vite (a native-module dev server with its own production build step) and others. The names change over time, so describe the ideas and say you would pick based on the framework and the team.

The Node script below writes two small files into a temporary folder and bundles them with esbuild. The result is a single minified file. The function that main.js never calls is not in the output, and the bundle runs and prints the greeting.

javascript
import { build } from 'esbuild';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync } from 'node:child_process';

const dir = mkdtempSync(join(tmpdir(), 'bundle-'));
writeFileSync(join(dir, 'greet.js'), "export const greet = (n) => 'Hello, ' + n;\nexport const unused = () => 'never called';\n");
writeFileSync(join(dir, 'main.js'), "import { greet } from './greet.js';\nconsole.log(greet('Asha'));\n");

const result = await build({
  entryPoints: [join(dir, 'main.js')], bundle: true, minify: true,
  format: 'iife', write: false, metafile: true,
});
const code = result.outputFiles[0].text;
console.log('output files:', result.outputFiles.length);
console.log('unused function in bundle:', code.includes('never called'));
console.log('inputs:', Object.keys(result.metafile.inputs).map((p) => p.split('/').pop()).sort().join(', '));
console.log('bundle prints:', execFileSync('node', ['-e', code]).toString().trim());

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and esbuild 0.28. The output was identical in two runs. Only esbuild was run, not webpack, Rollup or Vite.

Key points

  • A bundler follows imports to build a module graph from an entry point.
  • It transforms, tree shakes, minifies, splits and emits hashed files.
  • Native modules work, but deep import chains cost round trips.
  • Bundlers normalise package formats and non-JS assets.
  • Choose a tool by framework and team, not by trend.

Common mistakes

  • Saying a bundler is only for minification.
  • Believing HTTP/2 makes bundling pointless in every case.
  • Bundling everything into one huge file and ignoring code splitting.
  • Naming a tool without describing what it does.

Follow-ups

  • What is the difference between a bundler and a transpiler?
  • How does a dev server differ from a production build?
  • What is a module graph used for besides bundling?

Tips

  • List the five steps in order.
  • Give one honest reason to skip a bundler for a small project.
44.frontend-0044Mediummid

How does tree shaking work, and what stops it from removing code you do not use?

Tree shaking removes exports that nothing imports. It relies on the static shape of ES module import and export statements, so CommonJS modules cannot be shaken well, and code with side effects at the top level is kept unless the package says it has none with the sideEffects field.

Full answer

Tree shaking is dead code elimination across modules. The bundler builds the graph, marks which exports are used, and drops the rest.

It works because ES module import and export are static: they are at the top level and use string literals. The tool can read them without running the code. CommonJS require is a function call, so the target can be computed at run time, and module.exports can be changed at any time. A bundler usually has to keep the whole module.

What blocks tree shaking:

  • CommonJS or UMD packages, or code compiled to CommonJS by a tool before bundling.
  • Top-level code with side effects, such as calling a function, changing a global or patching a prototype. The bundler cannot tell if removing it is safe.
  • Barrel files that re-export everything, when the package or the bundler cannot see that the re-exports are pure.
  • Classes with static initialisers and decorators, in some setups.
  • Dynamic access such as import * as all followed by all[name].

Helpers:

  • Publish and import ES module builds. Packages can offer them through the module or exports fields.
  • The sideEffects field in package.json. "sideEffects": false tells the bundler that a file is safe to drop when its exports are unused. List the files that really have effects, such as a CSS import or a polyfill.
  • Pure annotations such as /* @__PURE__ */ on a call mark it as removable if its result is unused.
  • Import named exports directly, from specific paths when needed.

Measure with a bundle analyser. Do not assume that shaking worked.

The script below builds four small cases with esbuild. An unused ES module export disappears. An unused CommonJS export stays. A module with a top-level console.log keeps the log call, unless sideEffects is false, and then the whole file is removed. The behaviour of other bundlers can differ in details.

javascript
import { build } from 'esbuild';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

async function bundle(files, pkg) {
  const dir = mkdtempSync(join(tmpdir(), 'shake-'));
  for (const [name, text] of Object.entries(files)) writeFileSync(join(dir, name), text);
  if (pkg) writeFileSync(join(dir, 'package.json'), JSON.stringify(pkg));
  const r = await build({ entryPoints: [join(dir, 'main.js')], bundle: true, write: false, format: 'iife' });
  return r.outputFiles[0].text;
}

const esm = await bundle({
  'main.js': "import { used } from './lib.js'; console.log(used);",
  'lib.js': "export const used = 1; export const UNUSED_ESM = 'x';",
});
const cjs = await bundle({
  'main.js': "const { used } = require('./lib.js'); console.log(used);",
  'lib.js': "exports.used = 1; exports.UNUSED_CJS = 'x';",
});
const lib = { 'main.js': "import { unused } from './lib.js';", 'lib.js': "export const unused = 1; console.log('lib loaded');" };
const noFlag = await bundle(lib);
const withFlag = await bundle(lib, { sideEffects: false });

console.log('unused ESM export removed:', !esm.includes('UNUSED_ESM'));
console.log('unused CommonJS export removed:', !cjs.includes('UNUSED_CJS'));
console.log('side effect kept without flag:', noFlag.includes('lib loaded'));
console.log('side effect kept with sideEffects false:', withFlag.includes('lib loaded'));

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and esbuild 0.28. The output was identical in two runs. Other bundlers can treat these cases differently, and only esbuild was run.

Key points

  • Tree shaking removes unused exports using static import and export statements.
  • CommonJS is dynamic, so it usually cannot be shaken.
  • Top-level side effects are kept unless the package declares sideEffects false.
  • Pure annotations and named imports help the tool.
  • Check the result with a bundle analyser.

Common mistakes

  • Importing a whole library with a default or namespace import when one function is needed.
  • Setting sideEffects false on a package whose files patch globals or import CSS.
  • Assuming a library is shakeable because it is small in the docs.
  • Compiling to CommonJS before the bundler sees the code.

Follow-ups

  • What does /* @__PURE__ */ tell the bundler?
  • Why are barrel files a common cause of large bundles?
  • How do you find which import added the most bytes?

Tips

  • Start from why ES modules are shakeable, then list the blockers.
  • Mention sideEffects as the knob that library authors control.
45.frontend-0045Mediummid

What is code splitting, and how does dynamic import() reduce the JavaScript a user downloads on first load?

Code splitting breaks the bundle into chunks that load when needed. A dynamic import() returns a promise and tells the bundler to put that module in a separate chunk, so heavy code, such as a chart library or a rarely visited route, is not downloaded until the user needs it.

Full answer

A single bundle makes every visitor download and parse the code of every page. Code splitting cuts the download for the first view, which helps LCP and INP, since less JavaScript must be compiled and run.

Ways to split:

  • Route-based. Each page is its own chunk, loaded on navigation. Most frameworks offer this with a lazy route helper, such as React.lazy with Suspense or a framework's built-in routing.
  • Component-based. Load a heavy widget only when it opens: a rich text editor, a map, a chart, a PDF viewer.
  • Vendor or shared chunks. Split code that many pages share, so it is cached once. Hashed names keep the cache valid between releases.

The tool for it is import(). Unlike a static import, it can be called anywhere, takes a string and returns a promise for the module. The bundler sees the call, creates a chunk and loads it by URL at run time.

Trade-offs to mention:

  • Too many small chunks make a waterfall of requests. A chunk that is needed on every route should not be lazy.
  • The first interaction with a lazy feature waits for the download. Reduce the wait with a prefetch on hover, on idle time or with <link rel="modulepreload">.
  • Show a loading state and an error state. A chunk request can fail on a bad network or after a deploy removed the old file.
  • A failed import after a deploy is a classic bug. Keep old chunks for a while, and reload the page when an import fails with a version mismatch.

The script uses esbuild with splitting turned on. main.js calls import('./report.js') inside a function. The result is two output files, and the code of the heavy module is only in the second one.

javascript
import { build } from 'esbuild';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

const dir = mkdtempSync(join(tmpdir(), 'split-'));
writeFileSync(join(dir, 'report.js'), "export const render = () => 'HEAVY_REPORT_CODE';\n");
writeFileSync(join(dir, 'main.js'),
  "export async function openReport() { const m = await import('./report.js'); return m.render(); }\n");

const result = await build({
  entryPoints: [join(dir, 'main.js')], bundle: true, splitting: true,
  format: 'esm', outdir: join(dir, 'out'), write: false,
});
const files = result.outputFiles.map((f) => ({ name: f.path.split('/').pop(), text: f.text }));
console.log('output files:', files.length);
console.log('entry has heavy code:', files.find((f) => f.name === 'main.js').text.includes('HEAVY_REPORT_CODE'));
console.log('a lazy chunk has heavy code:', files.some((f) => f.name !== 'main.js' && f.text.includes('HEAVY_REPORT_CODE')));

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and esbuild 0.28. The output was identical in two runs. The chunks were not loaded in a browser, so prefetching and failure handling were not run.

Key points

  • Split by route, by heavy component and by shared vendor code.
  • Dynamic import() returns a promise and creates a separate chunk.
  • Too many chunks create request waterfalls.
  • Prefetch likely chunks and handle loading and failure states.
  • A deploy can remove old chunks. Plan for failed imports.

Common mistakes

  • Lazy loading code that every page needs.
  • No loading state or error handling for the dynamic import.
  • Importing the heavy module statically elsewhere, which pulls it back into the main bundle.
  • Deleting old hashed chunks right after a deploy.

Follow-ups

  • How do you prefetch a chunk without running it?
  • Why does a static import elsewhere defeat the split?
  • What happens when a chunk fails to load?

Tips

  • Explain the mechanism (import returns a promise) and the three ways to split.
  • Name the waterfall risk to show balance.
46.frontend-0046Easyfresher

What is a source map, and how do you use it to debug an error in minified production code safely?

A source map is a file that maps positions in the generated, minified code back to the original files, lines and names. DevTools and error monitoring tools use it to show readable stack traces. For production, upload maps to the monitoring service instead of serving them publicly if the source code is private.

Full answer

Browsers run the output of a build, not the source. After minification the whole app can be on one line with short names, so a stack trace such as at a (app.min.js:1:4821) says little.

A source map (.map file, JSON) records, for each position in the output, the original file, line, column and name. A comment at the end of the output file, //# sourceMappingURL=app.min.js.map, tells tools where to find it. DevTools loads it when it is open, and shows the original files in the Sources panel. Breakpoints and stack traces then refer to your code.

Options in a build:

  • sourcemap: 'external' or 'linked' writes a separate map file. The output can link to it or not.
  • inline puts the map into the output file as a data URL. This makes the file much larger. Use it in development only.
  • hidden source maps write the map without the comment, so that browsers do not load it, and the map can be sent to a monitoring tool.
  • Maps can include the original source text (sourcesContent), which makes them self-contained and reveals your code to anyone who gets the file.

Privacy and security: maps show your source. If that is a concern, do not serve them publicly. Upload them to your error tracker, which uses them on the server to translate stack traces, and keep them out of the web root. Obfuscation is not a security measure, so the secrets never belong in front-end code anyway.

Other points: the map must match the exact build, so name or version the files, and upload the map with the same release id. Mismatched maps give wrong lines and are worse than none.

Node can use maps too, with node --enable-source-maps. The script below builds a tiny file with minification and a map, runs it with and without that flag, and shows that the error stack points to app.js:3 only when the map is used.

javascript
import { build } from 'esbuild';
import { mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { spawnSync } from 'node:child_process';

const dir = mkdtempSync(join(tmpdir(), 'map-'));
writeFileSync(join(dir, 'app.js'),
  "function checkout(cart) {\n  if (cart.items.length === 0) {\n    throw new Error('Cart is empty');\n  }\n}\ncheckout({ items: [] });\n");
await build({
  entryPoints: [join(dir, 'app.js')], bundle: true, minify: true, sourcemap: 'linked',
  outfile: join(dir, 'out.js'), logLevel: 'silent',
});
const run = (flags) => spawnSync('node', [...flags, join(dir, 'out.js')], { encoding: 'utf8' }).stderr;
console.log('stack points to app.js:3 with maps:', run(['--enable-source-maps']).includes('app.js:3'));
console.log('stack points to app.js:3 without maps:', run([]).includes('app.js:3'));

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and esbuild 0.28. The output was identical in two runs. Browser DevTools and an error monitoring service were not used.

Key points

  • A source map maps minified code back to original files, lines and names.
  • A sourceMappingURL comment points tools to the map.
  • Use hidden or uploaded maps in production when the source is private.
  • The map must match the exact build and release.
  • Inline maps are for development only.

Common mistakes

  • Serving full maps publicly for a private code base without thinking about it.
  • Uploading a map from a different build than the deployed files.
  • Using inline source maps in production, which makes files large.
  • Believing minified code hides secrets.

Follow-ups

  • How does an error monitoring service use source maps?
  • What is the difference between a hidden and an external map?
  • Why does a map slow nothing for users who never open DevTools?

Tips

  • Describe what a map contains and how tools find it.
  • Mention the privacy decision for production.
47.frontend-0047Easyfresher

What are unit, integration and end-to-end tests in a front-end project, and how do you decide what to test at each level?

Unit tests check one function or component in isolation and are fast. Integration tests check several parts working together, such as a form with its validation and API calls. End-to-end tests drive a real browser through a user flow and are the slowest and most realistic. Use many cheap tests for logic and few expensive ones for critical flows.

Full answer

The three levels trade speed and precision against realism.

  • Unit tests. One unit: a pure function, a hook, a small component. They run in milliseconds, point to the exact line that broke, and are easy to write for logic such as price formatting, validation and reducers. They cannot tell you that the parts work together.
  • Integration tests. Several units with real wiring and fake edges: a component tree rendered with its state and a mocked network. They catch broken contracts between parts, such as a form that sends the wrong field. They run in a test runner with a simulated DOM, in seconds.
  • End-to-end (E2E) tests. A real browser against a running app, usually with a test backend. They prove that a user can log in and buy a course. They are slow, need data setup, and can be flaky, so keep the set small and aimed at critical paths.

The "test pyramid" suggests many unit tests, fewer integration tests and few E2E tests. Front-end teams also use the "testing trophy" idea, which puts most effort into integration tests, because the user-visible behaviour of a component depends on how its parts work together. Both models say the same practical thing: do not test everything at the top level.

Choosing the level:

  1. Pure logic with many cases: unit test with a table of inputs and outputs.
  2. A component or screen with state, forms or data loading: integration test through the rendered output.
  3. A flow that earns money or must not break (sign up, pay, enrol): E2E, one per flow.
  4. Visual details: a visual comparison tool or a manual check, because assertions on pixels are fragile.

Other checks that help: static types and lint (they catch a class of errors with no test), and accessibility checks in tests.

The snippet uses the built-in Node test runner. Two unit tests check small functions, and one test combines them, which is the smallest kind of integration test.

javascript
import test from 'node:test';
import assert from 'node:assert/strict';

const formatPrice = (cents) =>
  new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(cents / 100);
const cartTotal = (items) => items.reduce((sum, i) => sum + i.cents * i.qty, 0);

test('unit: formatPrice shows dollars and cents', () => {
  assert.equal(formatPrice(1999), '$19.99');
});
test('unit: cartTotal multiplies price by quantity', () => {
  assert.equal(cartTotal([{ cents: 500, qty: 2 }, { cents: 250, qty: 1 }]), 1250);
});
test('integration: the cart total is shown as a price', () => {
  const items = [{ cents: 500, qty: 2 }, { cents: 250, qty: 1 }];
  assert.equal(formatPrice(cartTotal(items)), '$12.50');
});

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Run with the Node test runner (node --test). Three tests passed in two runs. No browser test runner was used.

Key points

  • Unit: fast, isolated, precise. Integration: parts together. E2E: real browser, real flow.
  • Pyramid: many unit tests. Trophy: most effort in integration tests.
  • Choose the lowest level that can catch the bug.
  • Keep E2E tests few and focused on critical flows.
  • Types and lint are cheap tests too.

Common mistakes

  • Testing everything through the browser because it feels realistic.
  • Writing unit tests for implementation details that change often.
  • Counting coverage percent as the goal.
  • Leaving critical flows with no end-to-end test.

Follow-ups

  • Why are E2E tests slower and more fragile?
  • How do you decide whether to mock the network in an integration test?
  • What does a test of an implementation detail look like?

Tips

  • Describe each level by speed, cost and what it can catch.
  • Give one example of what you would test at each level.
48.frontend-0048Mediummid

What is the philosophy of Testing Library, and why do tests query by role instead of by class name or component internals?

Testing Library tests the page the way a user uses it: find elements by role, label or text, click, type and read what appears. Tests then survive refactors that keep behaviour, and a query by role also fails when the accessibility of the element is broken.

Full answer

A test that reads class names, component state or the number of calls to an internal function is tied to how the code is written. A refactor that keeps the behaviour breaks it. A bug that breaks the real behaviour can pass it. These are false failures and false confidence.

Testing Library suggests tests resemble real use. Its queries follow the order of preference:

  1. By role and accessible name: getByRole('button', { name: 'Save' }). This is how assistive tools see the page.
  2. By label text for form fields: getByLabelText('Email').
  3. By visible text, placeholder or display value.
  4. By test id (data-testid) only when nothing user-facing works.

Benefits: the query documents what a user sees, it checks that the element has the right role and name, and it does not care if the markup changes from a div to a section.

Other rules that follow from the idea:

  • Interact with events that a user causes: click, type, tab. Prefer the user-event library over raw event dispatch where it is available, because it also fires the intermediate events that the browser fires.
  • Assert on visible results, such as text, roles and states, not on component state.
  • Use findBy queries or waitFor for things that appear later, and avoid fixed sleeps.
  • Use queryBy to assert that something is absent, because getBy throws.
  • Mock the network edge and not the components in between.

Limits: a simulated DOM such as jsdom does not do layout, so tests about size, position or CSS need a real browser.

The script uses the DOM version of Testing Library with jsdom. It builds a toggle button, finds it by role and name, clicks it, and finds it again by the new name and its aria-pressed state. The old name no longer matches.

javascript
import { JSDOM } from 'jsdom';
import { getByRole, queryByRole, fireEvent } from '@testing-library/dom';

const { document } = new JSDOM('<!doctype html><body><div id="root"></div></body>').window;
const root = document.getElementById('root');

function mountToggle(parent) {
  let liked = false;
  const button = document.createElement('button');
  const render = () => {
    button.textContent = liked ? 'Liked' : 'Like';
    button.setAttribute('aria-pressed', String(liked));
  };
  button.addEventListener('click', () => { liked = !liked; render(); });
  render();
  parent.append(button);
}
mountToggle(root);

const button = getByRole(root, 'button', { name: 'Like' });
fireEvent.click(button);
console.log('found again by new name and state:', getByRole(root, 'button', { name: 'Liked', pressed: true }) === button);
console.log('old name gone:', queryByRole(root, 'button', { name: 'Like' }) === null);

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24, jsdom and @testing-library/dom. The output was identical in two runs. jsdom has no layout, and no component framework was used.

Key points

  • Test as a user does: find by role, label or text, then interact.
  • Prefer getByRole with a name, then label, then text, and test ids last.
  • Assert on visible output, not on component internals.
  • A role query also checks accessibility.
  • jsdom has no layout, so layout needs a real browser.

Common mistakes

  • Querying by CSS class or by component name.
  • Using test ids for everything.
  • Using getBy to assert that an element is not there.
  • Using fixed delays instead of findBy or waitFor.

Follow-ups

  • When is a test id acceptable?
  • What is the difference between getBy, queryBy and findBy?
  • Which behaviour needs a real browser instead of jsdom?

Tips

  • State the guiding idea in one sentence, then give the query order.
  • Say why role queries also help accessibility.
49.frontend-0049Mediummid

How do you test front-end code that calls an API without using the network, and which cases should you cover?

Replace the network edge with a controlled fake, such as a stubbed fetch or a mock service layer, and then test the success path, an HTTP error status, a network failure and the loading state. Mock as little as possible, so the code between the user action and the network is real.

Full answer

Real network calls make tests slow, flaky and dependent on data. The fix is to control the edge of your code that talks to the network.

Options:

  • Stub fetch for the test. Simple and good for small functions. A runner's mock helper can restore the original after each test.
  • Inject the dependency. Pass an api object or a fetch function into the code, and give the test a fake.
  • Intercept requests at the network level with a tool such as Mock Service Worker (MSW). The code under test calls the real fetch, and the interceptor answers. This keeps the tests closer to production code, and the same handlers can serve in development and in the browser tests.
  • Use a real test backend only in a few end-to-end tests.

Cases that deserve a test, since users meet all of them:

  1. Success: data is shown.
  2. Empty data: the empty state, not a blank page.
  3. HTTP error: fetch does not reject on 404 or 500. The code must check response.ok. A common bug is to call .json() on an error page.
  4. Network failure: fetch rejects with a TypeError. The user should see an error message and a way to retry.
  5. Slow response and loading state, and a canceled request when the user leaves.
  6. Race conditions: an old response arriving after a newer request.

Practical rules: reset mocks between tests, assert on what the user sees and on the request that was made (URL, method, body), and never let a test pass silently because an assertion sits in a callback that never ran. Return or await the promise.

The snippet tests a small loader with the Node test runner. It covers success, a 404, and a network failure, and checks that the request URL was correct.

javascript
import test, { mock } from 'node:test';
import assert from 'node:assert/strict';

async function loadCourses() {
  const res = await fetch('/api/courses');
  if (!res.ok) throw new Error(`Request failed: ${res.status}`);
  return res.json();
}

test('returns the list on success', async () => {
  const fake = mock.method(globalThis, 'fetch', async () => new Response(JSON.stringify(['HTML']), { status: 200 }));
  assert.deepEqual(await loadCourses(), ['HTML']);
  assert.equal(fake.mock.calls[0].arguments[0], '/api/courses');
  fake.mock.restore();
});

test('throws a clear error on HTTP 404', async () => {
  mock.method(globalThis, 'fetch', async () => new Response('missing', { status: 404 }));
  await assert.rejects(loadCourses(), /Request failed: 404/);
  mock.restoreAll();
});

test('rejects when the network fails', async () => {
  mock.method(globalThis, 'fetch', async () => { throw new TypeError('Failed to fetch'); });
  await assert.rejects(loadCourses(), /Failed to fetch/);
  mock.restoreAll();
});

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Run with the Node test runner (node --test). Three tests passed in two runs. MSW and a real component were not used.

Key points

  • Control the network edge. Do not hit real servers in unit or integration tests.
  • Options: stub fetch, inject a fake, or intercept requests with a tool such as MSW.
  • Test success, empty, HTTP error, network failure and loading.
  • fetch does not reject on 404 or 500. Check response.ok.
  • Reset mocks and await every promise.

Common mistakes

  • Mocking so much that the test checks only the mock.
  • Forgetting the HTTP error case because fetch did not throw.
  • Not awaiting the async code, so the test passes before the assertion runs.
  • Sharing mock state between tests.

Follow-ups

  • What does MSW do differently from stubbing fetch?
  • How would you test that a stale response is ignored?
  • How do you test a retry button?

Tips

  • List the cases, not only the tool.
  • Mention response.ok, since it is the classic trap.
50.frontend-0050Hardsenior

End-to-end tests pass on a developer machine and fail now and then in CI. How do you find the cause and make them reliable?

Flaky tests usually come from timing assumptions, shared state, uncontrolled data or environment differences. Replace fixed sleeps with auto-waiting assertions, isolate each test's data and state, control time and the network, and use traces from the failing CI run to see what happened.

Full answer

A flaky test is one that gives different results for the same code. It is costly because the team learns to ignore red builds. Retries hide it, they do not fix it.

Find the cause first. Collect evidence from the failed run: a trace, a video, a screenshot, the console and network log. Browser test tools can record a trace on the first retry. Then look for the usual causes.

  1. Timing. The test acts or asserts before the page is ready: sleep(500) is a guess that is right on a fast laptop and wrong on a slow runner. Fix: wait for a condition. Modern tools wait for elements to be visible, stable and enabled before an action, and web-first assertions retry until the expected state or a timeout.
  2. Shared state. Tests depend on order, on data left by another test, or on the same user account while running in parallel. Fix: create the data each test needs through the API, use unique names, and run each test in a fresh browser context.
  3. Uncontrolled external inputs. Real third-party services, the current date, random values, animations. Fix: mock or stub them, fix the clock, disable animation in the test build.
  4. Brittle selectors. CSS paths and indexes break when the layout changes. Fix: use roles, labels and stable test ids.
  5. Environment. CI has fewer CPUs, a different viewport, fonts and time zone. Fix: pin versions with a container image, set viewport and locale in the config, and reproduce with the same container locally.
  6. Real bugs. Some "flaky" tests are correct and reveal a race in the app, such as a request that races a navigation. Do not dismiss them.

Process: measure the failure rate by running the test many times, quarantine a flaky test with a ticket and an owner, and delete tests that nobody trusts.

The script uses Playwright against a page that shows a result after 300 milliseconds. A fixed 50 millisecond sleep reads an empty result. The auto-waiting call waits until the text appears. The results of a real CI environment were not reproduced.

javascript
import { chromium } from 'playwright-core';

const browser = await chromium.launch({
  executablePath: process.env.CHROME_PATH ?? '/usr/bin/google-chrome',
  args: ['--no-sandbox'],
});
const page = await browser.newPage();
await page.setContent(`<button id="go">Load</button><p id="result"></p>
<script>go.onclick = () => setTimeout(() => { result.textContent = 'Loaded'; }, 300);</script>`);

await page.click('#go');
await page.waitForTimeout(50);                       // fragile: guesses the delay
console.log('fixed sleep saw:', JSON.stringify(await page.textContent('#result')));

await page.getByText('Loaded').waitFor();            // waits for the condition
console.log('auto-wait saw:', JSON.stringify(await page.textContent('#result')));
await browser.close();

Run with Node 24.22.1. The output matched the text in the answer in two runs. Run with Node 24 and playwright-core with Chrome 156, using a local system Chrome. The output was identical in two runs. A CI environment, a trace viewer and parallel workers were not used. The path of the browser is set by CHROME_PATH.

Key points

  • Find the cause with traces and logs before changing anything.
  • Replace fixed sleeps with auto-waiting and web-first assertions.
  • Isolate state and data for each test, and run each in a fresh context.
  • Control time, network, randomness and animations.
  • Retries hide flakiness. Quarantine, own and fix.

Common mistakes

  • Adding retries or longer sleeps as the fix.
  • Writing selectors from the DOM structure.
  • Sharing one user account between parallel tests.
  • Ignoring a flaky test that points to a real race in the app.

Follow-ups

  • How do you measure the flake rate of one test?
  • What does auto-waiting check before a click?
  • When is a test not worth keeping?

Tips

  • Group causes into timing, state, external inputs, selectors and environment.
  • Say that evidence comes first and retries are not a fix.
51.frontend-0051Easyfresher

How does IntersectionObserver work, and how do you use it for lazy loading and infinite scroll instead of a scroll listener?

IntersectionObserver calls a callback when a watched element enters or leaves the viewport, or another root, by a given amount. The browser does the measuring, off your scroll handler, so it is cheaper and simpler than reading positions in a scroll event. Watch a sentinel element at the end of a list to load the next batch.

Full answer

A scroll listener runs on every scroll event, and reading getBoundingClientRect() inside it can force layout again and again. IntersectionObserver moves the work to the browser. You describe what to watch, and it reports changes.

Creating one: new IntersectionObserver(callback, options), then observer.observe(element). The callback receives a list of entries. Each entry has isIntersecting, intersectionRatio, target and boundingClientRect.

Options:

  • root: the scrolling container to use. The default null is the viewport.
  • rootMargin: grows or shrinks the root box, like CSS margin. A value such as '200px' fires before the element is visible, which hides loading delay.
  • threshold: the fraction of the target that must be visible, such as 0, 0.5 or an array.

Use cases:

  • Lazy loading images and components just before they are needed. For images, the loading="lazy" attribute does this natively and is simpler, but an observer lets you control more (data fetching, widgets, videos).
  • Infinite scroll: put a small sentinel element after the last item. When it intersects, load the next page and append items, and the sentinel moves down.
  • Analytics: record that an ad or a section was seen.
  • Highlighting the active section in a table of contents.

Care points:

  • Call unobserve or disconnect when done, to avoid leaks and repeated loads.
  • Guard against loading twice while a request is running.
  • Infinite scroll has costs for keyboard users who cannot reach the footer, and for memory. Offer a "Load more" button or pagination, and consider list virtualisation for very long lists.
  • The callback runs asynchronously, so the first call comes shortly after observe.

The page below has 10 rows of 100 pixels and a sentinel. The observer adds 10 more rows when the sentinel comes within 200 pixels of the viewport, up to 30. The test scrolls and counts the rows.

html
<style>
  body { margin: 0; }
  .row { height: 100px; border-bottom: 1px solid #ddd; }
</style>
<div id="list"></div>
<div id="sentinel"></div>
<script>
  let count = 0;
  function addRows(n) {
    for (let i = 0; i < n; i++) {
      const row = document.createElement('div');
      row.className = 'row';
      row.textContent = 'Row ' + (++count);
      list.append(row);
    }
  }
  addRows(10);
  const observer = new IntersectionObserver((entries) => {
    if (!entries[0].isIntersecting) return;
    if (count < 30) addRows(10);
    else observer.disconnect();
  }, { rootMargin: '200px' });
  observer.observe(sentinel);
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The check scrolled the page by script and counted rows after each step: 10, 20, then 30, and then no more. Scroll by a real touch device was not tested.

Key points

  • The browser reports when watched elements cross the viewport or a root.
  • Options: root, rootMargin and threshold.
  • Use a sentinel element for infinite scroll.
  • Use rootMargin to load before the element is visible.
  • Unobserve when done and guard against duplicate loads.

Common mistakes

  • Using a scroll listener with getBoundingClientRect on every event.
  • Forgetting that the callback also fires once at the start.
  • Not stopping when there is no more data, which loads forever.
  • Infinite scroll with no keyboard-friendly way to reach the footer.

Follow-ups

  • When is loading="lazy" enough?
  • How would you load the next page only once?
  • What does a threshold of 0.5 mean?

Tips

  • Contrast it with a scroll listener in one sentence.
  • Name the three options and give a use for rootMargin.
52.frontend-0052Mediummid

When should you use a Web Worker, and how does it keep the page responsive during heavy computation?

A Web Worker runs JavaScript on a separate thread with no DOM access. Send it data with postMessage and receive the result with a message event. This keeps the main thread free for input and painting during CPU-heavy work such as parsing a large file, image processing or search indexing.

Full answer

JavaScript on the main thread shares time with rendering and input. Long computations freeze the page. A dedicated worker has its own event loop and thread. The two sides cannot share variables. They communicate by messages.

Basics:

  • Create with new Worker(url), or from a Blob URL for inline code. Modules can be loaded with { type: 'module' }.
  • worker.postMessage(data) sends data. The data is copied with the structured clone algorithm, so it can be objects, arrays, Maps and typed arrays, but not functions or DOM nodes.
  • worker.onmessage receives results. Handle onerror and onmessageerror, and call worker.terminate() when it is not needed.
  • Large binary data can be transferred instead of copied: postMessage(buffer, [buffer]) moves an ArrayBuffer without a copy, and the sender then loses access to it. SharedArrayBuffer allows shared memory, but it needs cross-origin isolation headers.
  • Inside a worker there is no window or document. There are fetch, timers, IndexedDB and importScripts (or import in module workers).

Good uses: parsing big JSON or CSV, image or audio processing, encryption, diffing, search index building, and a heavy library that has no UI. Poor uses: tiny tasks, where the message cost is more than the work, and anything that needs the DOM.

Libraries such as Comlink wrap postMessage into promise-style calls. A pool of workers can use several cores. Service workers and shared workers are different kinds, with other lifecycles.

Practical points: build the worker with your bundler so the file is hashed and found. Check that CSP allows worker-src and blob: when you create Blob workers.

The page below starts a counter on the main thread with setInterval every 10 milliseconds, then sends 30 million loop steps to a worker. The counter keeps ticking while the worker computes. The test also runs the same loop on the main thread, where the counter does not tick.

html
<script>
  const src = `onmessage = (e) => {
    let sum = 0;
    for (let i = 0; i < e.data; i++) sum += i % 3;
    postMessage(sum);
  };`;
  const worker = new Worker(URL.createObjectURL(new Blob([src], { type: 'text/javascript' })));

  let ticks = 0;
  const timer = setInterval(() => { ticks += 1; }, 10);

  window.result = new Promise((resolve) => {
    worker.onmessage = (e) => { clearInterval(timer); resolve({ sum: e.data, ticks }); };
  });
  worker.postMessage(30000000);
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The worker ran for about 1 second, and the main thread timer kept ticking about 90 to 100 times. The same loop on the main thread allowed no ticks. Exact numbers vary by machine.

Key points

  • A worker is a separate thread with its own event loop and no DOM.
  • Communicate with postMessage. Data is structured-cloned.
  • Transfer large buffers to avoid copying.
  • Use for CPU-heavy work, not tiny tasks or DOM work.
  • Terminate workers and handle errors.

Common mistakes

  • Expecting to share variables or call DOM functions from a worker.
  • Sending huge objects back and forth in every frame.
  • Creating a new worker for every small task.
  • Forgetting error handling and termination.

Follow-ups

  • What is the cost of structured cloning?
  • When do you need SharedArrayBuffer?
  • How does a worker differ from a service worker?

Tips

  • State what a worker cannot do before what it can.
  • Give one good use and one poor use.
53.frontend-0053Mediummid

Which client-side storage options exist, and when would you choose IndexedDB over localStorage?

localStorage is a small, synchronous key-value store of strings, good for settings. IndexedDB is an asynchronous database of structured objects with indexes and transactions, good for large or complex data and offline apps. Cookies are sent with requests, sessionStorage ends with the tab, and the Cache API stores responses.

Full answer

Options and their roles:

  • Cookies: small (about 4 KB each), sent with every matching request, can be HttpOnly. Use them for sessions and server-visible state.
  • localStorage: string key-value pairs, synchronous, persists until cleared, shared by tabs of one origin. The usual limit is a few megabytes per origin, but it differs between browsers. Fine for a theme or a language choice.
  • sessionStorage: the same API, but limited to one tab and removed when it closes.
  • IndexedDB: a transactional object database. It stores structured-cloned values (objects, arrays, Blobs, typed arrays), supports indexes and range queries, and is asynchronous, so it does not block the main thread. It is available in workers.
  • Cache API: stores Request and Response pairs, used by service workers.

Why choose IndexedDB over localStorage:

  • Large data, such as downloaded lessons, drafts, or a local copy of a list for offline use. Quotas are usually much larger, but they depend on the disk space and the browser.
  • Structured data and queries, without turning everything into JSON strings.
  • Non-blocking access. localStorage.getItem blocks the main thread, so many reads on a hot path can hurt responsiveness.
  • Access from a worker, and transactions that keep related writes consistent.

Costs: the raw API is event-based and verbose, so teams wrap it in promises or use a small library. Schema changes need version upgrades in onupgradeneeded.

Rules for any storage:

  • Storage is per origin, and a user can clear it, so treat it as a cache that can disappear. Browsers can also evict data under storage pressure unless the site asks for persistence with navigator.storage.persist().
  • Do not store secrets or session tokens where scripts can read them.
  • Plan a migration for changes in the data format, and handle private browsing modes and quota errors.

The page below opens a database, writes an object, reads it back and shows that localStorage turns a number into a string.

html
<script type="module">
  const open = () => new Promise((resolve, reject) => {
    const req = indexedDB.open('schoolabe', 1);
    req.onupgradeneeded = () => req.result.createObjectStore('notes', { keyPath: 'id' });
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
  const wrap = (req) => new Promise((resolve, reject) => {
    req.onsuccess = () => resolve(req.result);
    req.onerror = () => reject(req.error);
  });
  const store = (db, mode) => db.transaction('notes', mode).objectStore('notes');

  const db = await open();
  await wrap(store(db, 'readwrite').put({ id: 1, text: 'Lesson 3 notes', tags: ['css'] }));
  const note = await wrap(store(db, 'readonly').get(1));
  localStorage.setItem('count', 42);
  window.out = { text: note.text, tags: note.tags, local: typeof localStorage.getItem('count') };
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. Checked in headless Chrome on a test origin. Quota, eviction, private browsing and other browsers were not tested.

Key points

  • Cookies are for server-visible state. localStorage is small, sync strings.
  • sessionStorage is per tab. Cache API stores responses.
  • IndexedDB stores structured objects asynchronously, with indexes and transactions.
  • Choose IndexedDB for large, structured or offline data.
  • Storage can be cleared, so treat it as a cache and keep secrets out.

Common mistakes

  • Storing tokens or personal data in localStorage.
  • Storing large JSON in localStorage and blocking the main thread.
  • Assuming the data will always be there.
  • Changing the stored shape without a version upgrade.

Follow-ups

  • What does navigator.storage.persist do?
  • How does a version upgrade work in IndexedDB?
  • Why is localStorage unavailable in a worker?

Tips

  • Describe each storage type in a line, then give the decision rule.
  • Mention eviction and quota to show you know the limits.
54.frontend-0054Hardsenior

A page must show a list of 100,000 rows. Why does a plain render become slow, and how does list virtualization fix it?

Every DOM node adds memory, style and layout cost, so 100,000 rows make the page slow to build, scroll and update. Virtualization renders only the rows in and near the viewport, inside a container sized as if all rows existed, and swaps the rows as the user scrolls.

Full answer

A row can contain several nodes. A hundred thousand rows mean hundreds of thousands of DOM nodes. The costs are:

  • Creating nodes and attaching listeners: a long task on first render.
  • Style calculation and layout: a change near the top can re-layout a huge tree.
  • Memory: each node and its styles stay in memory.
  • Slow scrolling and a bad INP, because any interaction waits for a large main-thread job.

Virtualization (windowing) avoids creating most of the rows.

  1. Make a scroll container with a fixed height and overflow: auto.
  2. Give an inner spacer the total height (rowHeight * rowCount), so the scrollbar is correct.
  3. On scroll, compute the first and last visible index from scrollTop and the container height. Add a small buffer on each side to avoid blank flashes.
  4. Render only those rows, and place them with transform: translateY(...) at the right offset.
  5. Reuse nodes when possible (recycling) to reduce work.

Fixed row height is the easy case. Variable heights need measurement and a cache of heights, with an estimate for rows not yet seen. Libraries such as TanStack Virtual or react-window handle this, and they cover details like sticky headers and horizontal scrolling.

Costs and edge cases:

  • Browser find-in-page does not find text in rows that are not in the DOM.
  • Screen readers see only the rendered rows. Provide aria-rowcount and aria-rowindex on grid-like lists, or choose pagination for content where users need the whole list.
  • Keyboard focus can be lost when its row is removed. Keep the focused row rendered.
  • Anchors, "jump to row" and restoring scroll position need an index-based API.

Alternatives: pagination, "Load more", server-side filtering and search, and the CSS property content-visibility: auto, which skips rendering work for off-screen content but keeps all nodes in the DOM.

The page below does the fixed-height version. The test checks that fewer than 30 row nodes exist at any time, and that after scrolling to the middle the list shows the correct item.

html
<div id="scroller" style="height:400px; overflow:auto; position:relative">
  <div id="spacer"></div>
  <div id="rows" style="position:absolute; top:0; left:0; right:0"></div>
</div>
<script>
  const total = 100000, rowHeight = 40, buffer = 5;
  spacer.style.height = total * rowHeight + 'px';

  function render() {
    const first = Math.max(0, Math.floor(scroller.scrollTop / rowHeight) - buffer);
    const last = Math.min(total, Math.ceil((scroller.scrollTop + scroller.clientHeight) / rowHeight) + buffer);
    rows.style.transform = `translateY(${first * rowHeight}px)`;
    rows.replaceChildren(...Array.from({ length: last - first }, (_, k) => {
      const row = document.createElement('div');
      row.style.height = rowHeight + 'px';
      row.textContent = 'Item ' + (first + k + 1);
      return row;
    }));
  }
  scroller.addEventListener('scroll', render, { passive: true });
  render();
</script>

Run in headless Chrome 156 through Playwright. Two full runs gave the same results. The check read the number of row nodes at the top and after scrolling to the middle (about 15 to 20 nodes) and the text of the visible row. Scrolling by touch, find-in-page and screen readers were not tested.

Key points

  • Large DOM trees cost memory, style, layout and slow interaction.
  • Virtualization renders only visible rows plus a buffer.
  • A spacer with the total height keeps the scrollbar honest.
  • Variable heights need measurement. Libraries handle this.
  • Costs: find-in-page, accessibility and focus need attention.

Common mistakes

  • Rendering every row and hoping a faster framework will fix it.
  • Forgetting the buffer, which causes blank areas while scrolling quickly.
  • Virtualizing without keeping the focused row in the DOM.
  • Ignoring accessibility and find-in-page for content users must read fully.

Follow-ups

  • How would you handle rows of different heights?
  • What does content-visibility auto do, and how does it differ?
  • How would you restore the scroll position after navigation?

Tips

  • Explain why it is slow before the fix, with the four costs.
  • Mention at least two drawbacks of virtualization.
55.frontend-0055Easyfresher

What is the same-origin policy, and which differences make two URLs different origins?

An origin is the scheme, host and port of a URL. The same-origin policy lets a page freely read data only from its own origin, and it limits scripts from reading data of other origins. A different scheme, host or port makes a different origin, and subdomains are different origins too.

Full answer

The same-origin policy is a core browser security rule. Without it, any page you open could use your logged-in session to read your email in another tab.

An origin has three parts: scheme, host and port. Two URLs are the same origin only if all three match.

  • https://schoolabe.com/courses and https://schoolabe.com/about are the same origin. The path does not matter.
  • http://schoolabe.com and https://schoolabe.com differ in scheme.
  • https://schoolabe.com and https://www.schoolabe.com differ in host. A subdomain is a different origin.
  • https://schoolabe.com and https://schoolabe.com:8443 differ in port. The default port of a scheme (443 for https, 80 for http) is the same as writing no port.

What the policy limits:

  • Scripts cannot read responses from other origins with fetch or XMLHttpRequest, unless the other server allows it with CORS.
  • Scripts cannot read the DOM of an iframe from another origin.
  • localStorage, IndexedDB and cookies are separated by origin or by site, depending on the storage type.

What it does not limit: a page can still embed images, scripts, stylesheets and frames from other origins, and it can send cross-origin form posts and simple requests. It limits reading. That is why CSRF exists and why third-party scripts are so powerful: a script loaded from another host runs with the origin of the page that loads it.

Related words:

  • Site is a larger idea: the scheme plus the registrable domain, such as schoolabe.com. app.schoolabe.com and www.schoolabe.com are the same site and different origins. Cookie rules (SameSite) use sites.
  • document.domain relaxation is deprecated and should not be used.
  • Where a page needs to talk to another origin on purpose, use CORS for data, and postMessage for windows.

The script compares several URLs with the standard URL class, which exposes the origin of each.

javascript
const base = 'https://schoolabe.com/courses';
const cases = [
  ['https://schoolabe.com/about', 'other path'],
  ['http://schoolabe.com/courses', 'other scheme'],
  ['https://www.schoolabe.com/courses', 'subdomain'],
  ['https://schoolabe.com:8443/courses', 'other port'],
  ['https://schoolabe.com:443/courses', 'default port written out'],
];
for (const [url, label] of cases) {
  console.log(`${new URL(url).origin === new URL(base).origin} - ${label}`);
}

Run with Node 24.22.1. The output matched the text in the answer in two runs.

Key points

  • An origin is scheme, host and port. The path is not part of it.
  • A subdomain or a different port is a different origin.
  • The policy limits reading cross-origin responses and frames, not embedding.
  • A site is broader than an origin, and cookies use sites.
  • CORS and postMessage are the controlled exceptions.

Common mistakes

  • Thinking the path is part of the origin.
  • Saying subdomains share an origin.
  • Believing the policy stops a page from sending cross-origin requests at all.
  • Mixing up origin and site.

Follow-ups

  • Why can a page include a script from a CDN?
  • How do origin and site differ for cookies?
  • What does a script from another origin run as?

Tips

  • Say the three parts, then give a table of examples.
  • End with what the policy does not stop.
56.frontend-0056Easyfresher

Which HTTP status codes must a front-end developer know, and how should fetch code react to 301, 401, 404, 429 and 500?

Status codes come in families: 2xx success, 3xx redirects, 4xx client errors and 5xx server errors. fetch only rejects on a network failure, so code must check response.ok and the status. A 401 should lead to sign in, a 404 to a not found message, a 429 to a wait based on Retry-After, and a 500 to a retry or an error message.

Full answer

The first digit tells the family.

  • 2xx: success. 200 OK, 201 Created, 204 No Content (success with no body, so do not call .json()).
  • 3xx: redirects. 301 and 308 are permanent, 302 and 307 are temporary. 304 Not Modified answers a conditional request and means "use your cached copy".
  • 4xx: the request was wrong or not allowed. 400 bad request, 401 not authenticated, 403 authenticated but not allowed, 404 not found, 409 conflict, 422 validation failed, 429 too many requests.
  • 5xx: the server failed. 500 internal error, 502 and 504 gateway problems, 503 unavailable (often with Retry-After).

Facts about fetch that cause bugs:

  • The promise rejects only when the request cannot complete, such as a network failure, a CORS block or an abort. A 404 or 500 is a resolved promise. Check response.ok (true for 200 to 299) or the status.
  • Redirects are followed by default. response.redirected tells you that it happened. With redirect: 'manual', a browser gives an opaque redirect response and not the real status, so Node and the browser differ here.
  • An error response can still have a body. Read it (response.json()) to show a specific message, but guard against a non-JSON error page.
  • 204 and 304 have no body.

What to do:

  • 401: the session ended. Try to refresh the token once, or send the user to sign in. Do not retry in a loop.
  • 403: tell the user that they lack permission. Signing in again will not help.
  • 404: show a not found state. For an API lookup, it may simply mean "no record".
  • 429: wait. Use the Retry-After header (seconds or a date) and back off.
  • 5xx: retry idempotent requests a few times with exponential backoff and jitter. Do not retry unsafe requests without an idempotency key.

The script starts a server with six routes and calls them with a helper that turns each status into a user-level decision.

javascript
import http from 'node:http';

const routes = {
  '/ok': [200, {}, '{"ok":true}'],
  '/moved': [301, { Location: '/ok' }, ''],
  '/login': [401, {}, '{"error":"no session"}'],
  '/missing': [404, {}, '{"error":"no such course"}'],
  '/busy': [429, { 'Retry-After': '2' }, '{"error":"slow down"}'],
  '/broken': [500, {}, '{"error":"database down"}'],
};
const server = http.createServer((req, res) => {
  const [status, headers, body] = routes[req.url];
  res.writeHead(status, { 'Content-Type': 'application/json', ...headers });
  res.end(body);
});
await new Promise((resolve) => server.listen(0, resolve));
const base = `http://localhost:${server.address().port}`;

async function decide(path) {
  const res = await fetch(base + path);          // resolves for every status
  if (res.redirected) return 'followed a redirect, then ' + res.status;
  if (res.ok) return 'use the data';
  if (res.status === 401) return 'ask the user to sign in';
  if (res.status === 429) return `wait ${res.headers.get('retry-after')}s, then retry`;
  if (res.status >= 500) return 'show an error and offer a retry';
  return 'show: ' + (await res.json()).error;
}
for (const path of Object.keys(routes)) console.log(path.padEnd(9), '->', await decide(path));
server.close();

Run with Node 24.22.1. The output matched the text in the answer in two runs.

Key points

  • 2xx success, 3xx redirect, 4xx client error, 5xx server error.
  • fetch rejects only on network-level failure. Check response.ok.
  • 401 is not signed in. 403 is not allowed.
  • 429 and 503 may carry Retry-After. Back off.
  • 204 and 304 have no body.

Common mistakes

  • Assuming fetch throws on 404 or 500.
  • Calling response.json() on a 204 or an HTML error page.
  • Retrying 401 or 403 requests in a loop.
  • Retrying unsafe requests such as payments without an idempotency key.

Follow-ups

  • What is the difference between 401 and 403?
  • How would you retry 503 responses safely?
  • What does 304 mean for the browser?

Tips

  • Give the families first, then the five codes in the question.
  • Point out the fetch trap early.
57.frontend-0057Hardsenior

A search box sometimes shows results for an older query after the user has typed more. Why does it happen, and how do you fix it?

Responses do not always come back in the order the requests were sent. If each response writes to the screen when it arrives, a slow old response can overwrite a newer one. Cancel the previous request with an AbortController, and also ignore any response that is not for the latest query.

Full answer

A user types "r", then "re", then "rea". Three requests leave in that order. Network and server time vary, so the answer for "r" can take 90 ms and the answer for "re" 10 ms. The page shows "re" first, then the late "r" result replaces it. The input says "rea" and the list shows results for "r". This is a race condition, and it is hard to reproduce on a fast local server.

Fixes, from basic to complete:

  1. Abort the previous request. fetch(url, { signal }) accepts the signal of an AbortController. When a new query starts, call controller.abort() on the old one. The old promise rejects with an AbortError, which the code must treat as normal, not as a failure. Aborting also saves bandwidth, though the server may still do the work.
  2. Guard with a token. Keep a counter or the latest query. When a response arrives, compare it with the latest, and drop it if it is old. This protects code paths where abort is not available, for example a library call.
  3. Debounce the input, so that fewer requests are sent while the user is typing. This reduces load but does not remove the race, because two requests can still overlap.
  4. Ignore results after unmount. A component that is gone must not set state. Aborting in the cleanup of an effect does both.
  5. Show loading and error states per latest query only, so that an old failure does not replace a new success.

Libraries such as TanStack Query and SWR handle keys, cancellation and caching, but the idea is the same, and an interviewer expects you to explain it.

The script simulates a search with different delays per query. The first version applies every response and ends with the result for "r". The second aborts the earlier calls and guards with an id, and shows only the latest. fetch with a real URL works the same way, because the signal is passed in the options.

javascript
const delays = { r: 90, re: 10, rea: 50 };
function search(query, signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve('results for ' + query), delays[query]);
    signal?.addEventListener('abort', () => {
      clearTimeout(timer);
      reject(Object.assign(new Error('aborted'), { name: 'AbortError' }));
    });
  });
}

// Version 1: every response is applied when it arrives.
let shown = '';
const naive = (q) => search(q).then((r) => { shown = r; });
await Promise.all(['r', 're', 'rea'].map(naive));
console.log('naive shows:', shown);

// Version 2: abort the old request and ignore old responses.
let controller, latest = 0, fixed = '';
async function onInput(q) {
  controller?.abort();
  controller = new AbortController();
  const id = ++latest;
  try {
    const r = await search(q, controller.signal);
    if (id === latest) fixed = r;
  } catch (e) {
    if (e.name !== 'AbortError') throw e;
  }
}
await Promise.all(['r', 're', 'rea'].map(onInput));
console.log('fixed shows:', fixed);

Run with Node 24.22.1. The output matched the text in the answer in two runs.

Key points

  • Responses can arrive out of order, so late old responses overwrite new ones.
  • Abort the previous request with AbortController, and treat AbortError as normal.
  • Also compare with the latest query id as a guard.
  • Debounce reduces load but does not remove the race.
  • Cancel in cleanup when the component goes away.

Common mistakes

  • Debouncing and thinking the race is solved.
  • Treating AbortError as a user-facing error.
  • Testing only on a fast local server where order is stable.
  • Letting an old failure replace a newer success.

Follow-ups

  • How would you test this race in a unit test?
  • What does abort do to a request that has already reached the server?
  • How do query libraries avoid the problem?

Tips

  • Explain the failure with a concrete order of responses.
  • Give abort and guard together as the answer.
58.frontend-0058Hardsenior

How do you build an optimistic update for a like button, and what goes wrong with rollback when several actions are in flight?

An optimistic update changes the screen at once and sends the request in the background. If the request fails, the change is undone. Restoring a saved snapshot is wrong when other actions finished in between, so undo only the failed action, by applying its inverse or by re-deriving state from a log of pending actions.

Full answer

Waiting for the server before showing a result makes simple actions feel slow. With an optimistic update the interface assumes success:

  1. Apply the change to local state at once.
  2. Send the request.
  3. On success, keep the state, and optionally replace it with the server's value.
  4. On failure, undo the change and tell the user.

The hard part is the undo. A common first version saves the old value and restores it on failure:

js
const prev = state.likes; state.likes += 1;
try { await api.like(); } catch { state.likes = prev; }

This breaks when two clicks are in flight. If click A fails after click B has already been applied, restoring A's snapshot also removes B's change, even though B succeeded. The screen is wrong until a refetch.

Better approaches:

  • Apply the inverse. On failure of A, subtract A's own change (likes -= 1) so that B stays.
  • Keep a list of pending actions, and compute the displayed state as the server state plus all pending actions. When one fails, remove it from the list, and the display is recomputed. This is what query libraries do with optimistic mutations.
  • After the queue settles, refetch the true state from the server so that the display cannot drift.
  • Disable or serialise actions that cannot be combined, such as "like" then "unlike" on the same item, or send only the latest intent.

Other points for a complete answer:

  • Use idempotent requests or an idempotency key, so that a retry does not double count.
  • Show a small failure message and a retry option, not only a silent rollback.
  • Not every action is a good fit. Payments and destructive actions should wait for the server.
  • Keep ordering rules on the server, or send the intended final state ("liked: true") instead of "toggle".

The script simulates two likes. The first request fails and the second succeeds. A snapshot rollback ends with the wrong count, and the inverse rollback keeps the successful like.

javascript
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// The first call fails after 30 ms, the second succeeds after 60 ms.
const makeApi = () => { let n = 0; return { like: async () => { n += 1; if (n === 1) { await sleep(30); throw new Error('offline'); } await sleep(60); } }; };

async function run(rollback) {
  const api = makeApi();
  const state = { likes: 3 };
  const like = async () => {
    const prev = state.likes;
    state.likes += 1;                       // optimistic
    try { await api.like(); }
    catch { rollback(state, prev); }
  };
  await Promise.all([like(), like()]);
  return state.likes;
}
console.log('snapshot rollback ends at:', await run((s, prev) => { s.likes = prev; }));
console.log('inverse rollback ends at:', await run((s) => { s.likes -= 1; }));

Run with Node 24.22.1. The output matched the text in the answer in two runs. The short snapshot rollback code shown in the answer text is the same pattern as the first run in the script and was not run on its own.

Key points

  • Optimistic UI applies the change first and confirms later.
  • On failure, undo only that action. Snapshot restore breaks with concurrent actions.
  • Use the inverse, or recompute from server state plus pending actions.
  • Refetch after the queue settles, and use idempotency keys.
  • Wait for the server when the action is costly or irreversible.

Common mistakes

  • Saving a snapshot and restoring it for every failure.
  • Silent rollback with no message to the user.
  • Optimistic updates for payments.
  • Sending toggle commands that can repeat and flip the wrong way.

Follow-ups

  • How do query libraries model optimistic mutations?
  • Why is an idempotency key useful here?
  • How do you handle a failure after the user left the page?

Tips

  • State the idea, show the naive rollback, then explain why it fails.
  • Say that you would send the intended end state and not a toggle.
59.frontend-0059Hardsenior

How would you build a small client-side data cache that shares in-flight requests and uses stale-while-revalidate, as data-fetching libraries do?

Keep a map from a request key to an entry that holds the data, the time it was fetched and any promise in flight. A get returns fresh data without a request, returns stale data at once while a background refetch runs, and lets concurrent callers for the same key share one promise.

Full answer

Data-fetching libraries such as TanStack Query and SWR are built on a small set of ideas, and a candidate should be able to describe them and sketch the core.

State per key:

  • data and the time it was stored (fetchedAt).
  • promise when a request is in flight.
  • an error, if the last attempt failed.

Rules:

  1. Fresh. If the data is younger than staleMs, return it. No request.
  2. Stale. If the data is older, return it immediately so that the screen is not blank, and start a background refetch. When it finishes, the entry is updated and subscribers are told.
  3. Missing. Start a request and wait for it.
  4. In-flight deduplication. If a request for the same key is already running, return the same promise. Ten components that need the same user profile cause one request.
  5. Key design. The key must contain every input that changes the answer: path, query values, user id. Serialise it in a stable way.
  6. Errors. Do not cache a failure as data. Keep stale data visible and show an error state, and retry with backoff.
  7. Invalidation. After a mutation, mark related keys as stale, or refetch them. Without it, the screen can show old data after a save.
  8. Memory. Remove entries that nobody uses after some time (garbage collection), and set a limit.

Extra features to name: refetch on window focus or reconnection, retries, pagination and infinite queries, request cancellation, and persistence to storage for fast restarts.

Risks: a long stale time shows old information, and a very short one loses the benefit. The right values depend on how fast the data changes and how bad a stale view is.

The script has a fake clock and a counter for the fetcher. Two concurrent calls make one fetch. A call within the fresh window makes none. A call after the window gets the old value at once, and the new value after the refetch.

javascript
function createCache(now) {
  const entries = new Map();
  return function get(key, fetcher, staleMs) {
    let e = entries.get(key);
    if (!e) { e = {}; entries.set(key, e); }
    const refetch = () => {
      if (!e.promise) {
        e.promise = fetcher().then((data) => { e.data = data; e.at = now(); }).finally(() => { e.promise = null; });
      }
      return e.promise;
    };
    if ('data' in e) {
      if (now() - e.at >= staleMs) refetch();        // stale: answer now, refresh behind
      return Promise.resolve(e.data);
    }
    return refetch().then(() => e.data);              // missing: wait, share the promise
  };
}

let clock = 0, calls = 0;
const get = createCache(() => clock);
const fetcher = async () => { calls += 1; return 'profile v' + calls; };

const [a, b] = await Promise.all([get('user:1', fetcher, 1000), get('user:1', fetcher, 1000)]);
console.log('two callers:', a, b, 'fetch calls:', calls);
clock = 500;
console.log('fresh:', await get('user:1', fetcher, 1000), 'fetch calls:', calls);
clock = 1500;
console.log('stale:', await get('user:1', fetcher, 1000), 'fetch calls:', calls);
await new Promise((r) => setTimeout(r, 10));
console.log('after refetch:', await get('user:1', fetcher, 1000));

Run with Node 24.22.1. The output matched the text in the answer in two runs.

Key points

  • Store data, fetch time and in-flight promise per key.
  • Fresh returns data. Stale returns data and refetches. Missing waits.
  • Concurrent callers share one in-flight promise.
  • Keys must include every input, and mutations must invalidate.
  • Plan for errors, memory limits and refetch triggers.

Common mistakes

  • Caching by URL while ignoring user id or locale.
  • Caching failed responses as if they were data.
  • Forgetting to invalidate after a mutation.
  • Starting a duplicate request for every component that mounts.

Follow-ups

  • How would you add subscribers so that the UI updates after a background refetch?
  • How does this change for infinite scrolling?
  • What would you persist across page loads?

Tips

  • List the per-key state, then the five rules.
  • Say how invalidation works, since many answers forget it.