JavaScript interview question: an async bug scorecard
Use a JavaScript async debugging question with runnable reference code, deterministic checks and a copyable interviewer scorecard for observed evidence.

On this page
Use this JavaScript interview question to record how a candidate reproduces and fixes stale search results. An engineering interviewer should judge the implementation; a recruiter can record evidence and assistance using the scorecard below. The exercise protects query, status, items and error when an older search finishes last.
This is author-designed fictional material, not an employer’s question or a validated selection instrument. Use it only when asynchronous JavaScript is relevant to the role’s technical screening.
Give one prompt and record assistance
Have an engineering interviewer run the reference before using it. The candidate handout contains the state contract below and only createBrokenSearchRunner from the first code block. Ask the candidate to add an exported createSearchRunner with the same dependencies. Both complete files and the expected output below are the evaluator reference, not the starting handout.
Set the tools, documentation access and hint policy in advance. OPM’s structured-interview guidance describes predetermined questions and common rating standards. The prompt, hints and scorecard here are this exercise’s design, not an OPM-validated assessment.
Use the same prompt and follow-up requirement for each administration. Record what assistance was given and what remains untested. Choose a different prompt from the question bank when the role requires a different skill.
Agree on the complete search state
The latest invocation owns query, status, items and error. Every call invalidates earlier calls, including repeated text and cleared input.
Assume rawQuery is a string. The injected search(query) returns a promise for an array of strings, but may throw synchronously or reject later. The injected render(state) is synchronous and does not throw. All calls in a scenario share one runner instance.
Each render receives a complete state:
| Status | Query | Items | Error |
|---|---|---|---|
idle |
Empty string | Empty array | null |
loading |
Trimmed nonempty query | Empty array | null |
success |
That query | Returned array, including [] |
null |
error |
That query | Empty array | Original failure reason |
Creating a runner emits nothing until you call run. Calling it with whitespace trims to an empty query, immediately renders idle and never calls search. A nonempty query immediately renders loading, clearing previous items and errors.
A search returning [] emits success; clearing emits idle without a search.
The runner stores a thrown or rejected reason unchanged in error. Its returned promise fulfills after handling that invocation, including a search failure or ignored stale outcome. Callers inspect emitted state for a search error; they should not expect that error to reject run.
Evaluator reference: broken and guarded runners
Save this reference as stale-search.mjs. The two files were checked with Node.js v26.5.0. Node’s ECMAScript module documentation describes .mjs as an explicit module marker and supports the second file’s top-level await.
Both render the same state shape. The broken runner leaves old completions unguarded; the second adds ownership checks.
export function createBrokenSearchRunner(search, render) {
return async function run(rawQuery) {
const query = rawQuery.trim();
if (!query) {
render({ query, status: "idle", items: [], error: null });
return;
}
render({ query, status: "loading", items: [], error: null });
try {
const items = await search(query);
render({ query, status: "success", items, error: null });
} catch (error) {
render({ query, status: "error", items: [], error });
}
};
}
export function createSearchRunner(search, render) {
let latest;
return async function run(rawQuery) {
const token = {};
latest = token;
const query = rawQuery.trim();
if (!query) {
render({ query, status: "idle", items: [], error: null });
return;
}
render({ query, status: "loading", items: [], error: null });
try {
const items = await search(query);
if (token !== latest) return;
render({ query, status: "success", items, error: null });
} catch (error) {
if (token !== latest) return;
render({ query, status: "error", items: [], error });
}
};
}
await suspends the surrounding async function, not another invocation. Awaiting a rejected promise throws its rejection reason, as MDN’s await reference explains. The direct search(query) call is also inside try, so a synchronous throw reaches catch.
The guarded runner assigns a fresh object to latest before checking for empty input. Each invocation retains its token. MDN’s strict equality reference explains object identity: token !== latest identifies an invocation superseded by another call.
Comparing query text would fail when two calls both search for alpha. The identity belongs to the invocation, not its text.
Evaluator reference: controlled completion checks
Save stale-search-check.mjs beside the first file. The local deferred helper exposes promise resolution and rejection controls. The harness records calls and states so checks choose completion order explicitly.
Each scenario settles a chosen promise, then awaits its run call. No timer determines the result.
import assert from "node:assert/strict";
import {
createBrokenSearchRunner,
createSearchRunner,
} from "./stale-search.mjs";
function deferred() {
let resolve;
let reject;
const promise = new Promise((yes, no) => {
resolve = yes;
reject = no;
});
return { promise, resolve, reject };
}
function harness(factory = createSearchRunner) {
const calls = [];
const states = [];
const run = factory(query => {
const work = deferred();
calls.push({ query, ...work });
return work.promise;
}, state => states.push(state));
const last = () => states[states.length - 1];
return { run, calls, states, last };
}
async function trace(factory) {
const h = harness(factory);
const a = h.run("alpha");
const b = h.run("beta");
h.calls[1].resolve(["beta result"]);
await b;
h.calls[0].resolve(["alpha result"]);
await a;
return h.states.map(s => `${s.query}:${s.status}`).join(" -> ");
}
console.log("broken: " + await trace(createBrokenSearchRunner));
console.log("guarded: " + await trace(createSearchRunner));
async function check(name, scenario) {
await scenario(harness());
console.log("PASS " + name);
}
await check("stale success", async h => {
const a = h.run("alpha");
const b = h.run("beta");
h.calls[1].resolve(["beta result"]);
await b;
const before = h.states.length;
h.calls[0].resolve(["alpha result"]);
await a;
assert.equal(h.states.length, before);
assert.deepEqual(h.last(), {
query: "beta", status: "success", items: ["beta result"], error: null,
});
});
await check("stale rejection while beta is pending", async h => {
const a = h.run("alpha");
const b = h.run("beta");
const before = h.states.length;
h.calls[0].reject(new Error("old failure"));
await a;
assert.equal(h.states.length, before);
assert.deepEqual(h.last(), {
query: "beta", status: "loading", items: [], error: null,
});
h.calls[1].resolve(["beta result"]);
await b;
assert.equal(h.last().status, "success");
});
await check("latest rejection", async h => {
const reason = new Error("latest failure");
const done = h.run("alpha");
h.calls[0].reject(reason);
await done;
assert.deepEqual(h.last(), {
query: "alpha", status: "error", items: [], error: reason,
});
});
await check("clearing invalidates alpha", async h => {
const a = h.run("alpha");
await h.run(" ");
assert.equal(h.calls.length, 1);
const before = h.states.length;
h.calls[0].resolve(["alpha result"]);
await a;
assert.equal(h.states.length, before);
assert.deepEqual(h.last(), {
query: "", status: "idle", items: [], error: null,
});
});
await check("same text starts a new invocation", async h => {
const a = h.run("alpha");
const b = h.run(" alpha ");
assert.deepEqual(h.calls.map(call => call.query), ["alpha", "alpha"]);
h.calls[1].resolve(["new result"]);
await b;
const before = h.states.length;
h.calls[0].resolve(["old result"]);
await a;
assert.equal(h.states.length, before);
assert.deepEqual(h.last(), {
query: "alpha", status: "success", items: ["new result"], error: null,
});
});
await check("empty result is a successful search", async h => {
const done = h.run("alpha");
h.calls[0].resolve([]);
await done;
assert.deepEqual(h.last(), {
query: "alpha", status: "success", items: [], error: null,
});
});
const reason = new Error("synchronous failure");
const states = [];
const run = createSearchRunner(() => { throw reason; }, state => {
states.push(state);
});
await run("alpha");
assert.deepEqual(states, [
{ query: "alpha", status: "loading", items: [], error: null },
{ query: "alpha", status: "error", items: [], error: reason },
]);
console.log("PASS synchronous throw");
Run the evaluator checks from that directory:
node --unhandled-rejections=strict stale-search-check.mjs
Expected output:
broken: alpha:loading -> beta:loading -> beta:success -> alpha:success
guarded: alpha:loading -> beta:loading -> beta:success
PASS stale success
PASS stale rejection while beta is pending
PASS latest rejection
PASS clearing invalidates alpha
PASS same text starts a new invocation
PASS empty result is a successful search
PASS synchronous throw
Both traces start alpha, then beta. Beta finishes first; the broken runner later replaces its result with alpha’s. The guarded runner prevents that obsolete render.
React’s official data-fetching example independently describes responses arriving in a different order from their requests and ignores obsolete responses. This exercise isolates the ordering rule in plain JavaScript; it does not implement React cleanup or a browser interface.
Observe pending state as well as final results
The stale-rejection check verifies an intermediate state, before beta finishes. After alpha fails, beta must still own {query: "beta", status: "loading", items: [], error: null}. Checking only the eventual beta result could miss an incorrect error displayed while it was pending.
The evaluator assertions cover these obligations:
| Case | Required observation |
|---|---|
| Old success after beta succeeds | No additional render; beta’s items remain. |
| Old rejection while beta is pending | No additional render; beta remains loading without an error. |
| Latest rejection | Error state contains the original reason. |
| Cleared input while alpha is pending | No second search; alpha cannot replace idle. |
| Same text submitted again | Both searches receive trimmed alpha; only the newer result remains. |
Latest search returns [] |
Success with no items, not idle. |
| Search throws before returning | Loading is followed by error; run fulfills. |
Both success and catch need ownership checks. A handled search failure becomes state; it does not reject run under this contract. MDN’s async function reference explains that async calls return promises and uncaught exceptions reject them.
There is no finally block. Later cleanup that renders state would need the same ownership rule: MDN’s try…catch reference explains that finally runs even after a return. This is a control-flow warning, not a demonstrated faulty-finally implementation.
These checks cover selected schedules for one runner with a synchronous, nonthrowing renderer. They are not exhaustive proof; obsolete searches keep running.
Copy the interview observation scorecard
Record the candidate’s evidence against each criterion. Use Observed, Observed after hint or Not observed. Describe partial evidence in the notes; absence of evidence in this exercise is not a general ability judgment.
| Criterion | Evidence to record | Observation and notes |
|---|---|---|
| Reproduces the bug | Starts alpha then beta; makes beta finish first and shows alpha overwriting it. | Label; trace; hints given. |
| Protects state ownership | Gives each invocation fresh identity; guards success and failure; preserves beta’s pending state. | Label; relevant code and explanation. |
| Checks boundaries | Covers clear, repeated trimmed text, empty success and synchronous throw under the contract. | Label; cases checked or still missing. |
| Explains a requirement change | Distinguishes ignoring from cancellation; revises assumptions and tests before changing behavior. | Label; reasoning and unresolved questions. |
Use the same hint sequence: ask which invocation owns the visible state, then what happens when text repeats or clears. Record which hint was needed. Clarifying the supplied contract is separate from giving a solution hint.
For the debrief, ask the candidate to retain previous items while loading. Have them revise the contract and assertions first, as with clarifying the selection rule in the worked Python question. The supplied implementation tests the original requirement, not this variation.
An engineering interviewer reviews the implementation and notes before any hiring discussion. Do not total these labels into a pass score. Broader tool evaluation needs a separate pilot scorecard.
Prepin runs AI technical interviews by voice and live coding, with scored reports for recruiters. See how screening works.
Frequently asked questions
Can a nontechnical recruiter administer this alone?
Have an engineering interviewer own the code review and technical follow-up. A recruiter can provide the agreed prompt and record observations, questions and hints. Matching a candidate’s explanation to the reference by wording alone is insufficient.
Does passing the checks establish job readiness?
No. It shows the supplied implementation met the selected checks under the stated contract. This exercise has no validated hiring cutoff, job-performance prediction or claim to measure every JavaScript skill.
Does the token stop the old request?
No. It prevents obsolete completions from rendering state. The supplied search continues until it settles; cancellation would require a separate contract and implementation.
Sources
Prepared with AI assistance. Official documentation checked November 25, 2026. The exercise, hints and observation record are author-designed. The scripts were checked with Node.js v26.5.0; results do not establish browser integration, production readiness or hiring validity.
- OPM: Structured Interviews, current undated guidance; its consistency principles do not validate this exercise.
- MDN: await, modified November 23, 2026.
- MDN: async function, modified November 17, 2026.
- MDN: Strict equality, modified November 23, 2026.
- MDN: try…catch, modified March 9, 2026; stable control-flow definitions checked live.
- React: Fetching data with Effects, current undated documentation.
- Node.js: ECMAScript modules, current undated documentation.
Screen engineers before the first call
Send candidates one link. Prepin runs the technical voice interview and live coding, then gives you a scored report.
See how screening works →Practice the interview out loud
Run a realistic AI mock interview for your target role and get feedback on every answer.
Start a mock interview →