Skip to content

    Frontend System Design

    JavaScript, Browser and React Interview Questions

    Ten checkable JavaScript, browser and React interview questions, each answered with a rule, its mechanism and a source from MDN or react.dev, plus Node runs.

    By Published 11 min read

    • frontend-system-design
    • interview-questions
    • javascript
    • react
    Share

    What you'll learn: By the end of this lesson you will be able to answer ten common JavaScript, browser and React interview questions with a short answer, the mechanism behind it and a source you can open, predict the output of snippets that were actually run under Node, and spot the follow-up question each answer invites.

    Think of a driving test. The examiner does not want a speech about engines. They want you to name the rule, show you understand why it exists, and handle the "what if" they ask next. Technical questions work the same way: a one-line answer is the start, and the follow-up shows whether the rule is understood or memorised.

    This lesson is a small bank of questions where every answer can be checked. Each cites the page it comes from, and the code was run, with the output shown as it appeared. It does not claim anything about how often a question is asked or what any company asks: no such data was read. For how to run the whole conversation, see the lesson on the front-end architect interview framework (planned; plain text for now).

    The core idea

    A good answer has four parts, in this order: the rule (one sentence), the mechanism (why it behaves that way), a small demonstration (a few lines you could type), and the edge (where the rule stops holding, or the cost of using it). Questions in this bank are chosen so the rule is documented, the demonstration is short, and the edge exists.

    Figure 1. Where each answer lives

    Three places an interview answer comes fromQuestion to Language rules; Question to Browser APIs; Question to React model; Language rules to Answer; Browser APIs to Answer; React model to AnswerQuestion: one sentenceQuestionone sentenceLanguage rules: scope, equality, promisesLanguage rulesscope, equality,promisesBrowser APIs: events, fetch, scriptsBrowser APIsevents, fetch,scriptsReact model: state, keys, effectsReact modelstate, keys,effectsAnswer: rule, mechanism, demo, edgeAnswerrule, mechanism,demo, edge

    How to read this: first decide which layer owns the behaviour. A "why did my number not change" question is a React-model question even though the code is JavaScript.

    Snippets below ran under Node 26.13.1; the React snippets ran with React 19.3.1 under jsdom (an emulated DOM, not a real browser, so nothing below claims anything about layout or painting).

    Part 1: the language

    Q1. What does a closure capture, and why do var and let differ in a loop?

    Rule. MDN defines a closure as "a function bundled together (enclosed) with references to its surrounding state (the lexical environment)". Closures are created every time a function is created. Mechanism. A var is function-scoped, so a loop that declares var i gives every callback the same single variable. For a let in a for header, MDN says a new lexical scope with new variables is created after each iteration body, so each callback sees its own copy.

    Illustration 1: the minimal example

    const fnsVar = [];
    for (var i = 0; i < 3; i++) fnsVar.push(() => i);
    console.log("var:", fnsVar.map((f) => f()));
    const fnsLet = [];
    for (let j = 0; j < 3; j++) fnsLet.push(() => j);
    console.log("let:", fnsLet.map((f) => f()));
    try { console.log(tdz); let tdz = 1; } catch (e) { console.log(e.name); }

    Output from this run:

    var: [ 3, 3, 3 ]
    let: [ 0, 1, 2 ]
    ReferenceError

    Edge. The third line is the temporal dead zone: MDN says a let, const or class binding is in the zone from the start of the block until execution reaches its declaration, and reading it throws ReferenceError, unlike var, which gives undefined. Follow-up to expect: "How would you fix the var version without let?" MDN's page shows creating a new lexical environment per callback with a factory function.

    Q2. == or ===? What is typeof null?

    Rule. MDN says == converts types before comparing and === does not (different types give false), and that strict equality is "almost always the correct comparison operation to use". Object.is differs from === only for NaN and signed zeros. typeof null is "object": MDN explains this as a leftover of the first implementation, and says a fix that would have returned "null" was proposed and rejected.

    console.log(typeof null);
    console.log(NaN === NaN, Object.is(NaN, NaN));
    console.log(0 === -0, Object.is(0, -0));
    console.log(null == undefined, null === undefined);
    console.log([NaN].indexOf(NaN));
    object
    false true
    true false
    true false
    -1

    Edge. null == undefined is true by the loose-equality algorithm: if one operand is null or undefined, the other must be too. Some teams allow that one idiom and ban the rest. indexOf uses strict equality, so it never finds NaN.

    Q3. In what order does this log, and why?

    Rule. Synchronous code finishes first; then the microtask queue is drained; a timer callback is a separate task that runs later. MDN's microtask guide says one task runs per event-loop iteration, then microtasks run until the queue is empty, and "the browser may choose to update rendering". setTimeout with a delay of 0 is "placed on a queue and scheduled to run at the next opportunity; not immediately". MDN's await page says the code after an await resumes as a microtask, even when the value is not a promise.

    Figure 2. One turn of the loop

    sequenceDiagram accTitle: Order of synchronous code, microtasks and a timer accDescr: The script runs synchronously and queues a timer task, a promise callback, a queueMicrotask callback and an await continuation. When the script ends, the microtask queue is drained in order, then the timer task runs as a later task. participant S as Script (one task) participant M as Microtask queue participant T as Timer task queue S->>T: setTimeout(log 4, 0) S->>M: promise.then(log 3) S->>M: queueMicrotask(log 3b) S->>M: await continuation (log 3c) Note over S: script ends, stack is empty M->>M: run 3, 3b, 3c in order T->>T: next task: log 4

    How to read this: time runs downward. Everything the script enqueues in the microtask queue runs before the timer task, even though the timer was queued first.

    console.log("1 sync");
    setTimeout(() => console.log("4 timer"), 0);
    Promise.resolve().then(() => console.log("3 promise"));
    queueMicrotask(() => console.log("3b microtask"));
    (async () => { console.log("2 async body, before await"); await null; console.log("3c after await"); })();
    console.log("2b sync end");
    1 sync
    2 async body, before await
    2b sync end
    3 promise
    3b microtask
    3c after await
    4 timer

    Edge. MDN warns that a microtask that keeps queueing microtasks can keep the loop busy forever, because newly added microtasks run before the next task. The event-loop lesson (/learning/frontend-event-loop-main-thread) has the full model.

    Q4. Promise.all, allSettled, any or race?

    Rule, from MDN: all fulfills when all fulfill and rejects with the first rejection; allSettled fulfills when all settle, with an outcome object per promise; any fulfills with the first fulfillment and rejects with an AggregateError only when all reject; race settles with the first promise to settle, whether it fulfills or rejects.

    const ok = (v, ms) => new Promise((r) => setTimeout(() => r(v), ms));
    const bad = (m, ms) => new Promise((_, r) => setTimeout(() => r(new Error(m)), ms));
    const trio = () => [ok("A", 10), bad("B failed", 20), ok("C", 30)];
    console.log("all:", await Promise.all(trio()).then(String, (e) => "rejected " + e.message));
    console.log("allSettled:", JSON.stringify((await Promise.allSettled(trio())).map((r) => r.status)));
    console.log("any:", await Promise.any([bad("x", 5), ok("C", 15), ok("D", 30)]));
    console.log("race:", await Promise.race([bad("fast failure", 5), ok("C", 15)]).then(String, (e) => "rejected " + e.message));
    all: rejected B failed
    allSettled: ["fulfilled","rejected","fulfilled"]
    any: C
    race: rejected fast failure

    Edge. all and race do not cancel the promises that lose; they only stop waiting. Real cancellation needs an AbortController (see the lesson on request cancellation, retries and timeouts).

    Figure 3. Choosing a combinator

    flowchart TD accTitle: Choosing a promise combinator accDescr: A decision tree. If every result is needed, use all, which rejects on the first rejection. If you want every outcome even when some fail, use allSettled. If the first success is enough, use any. If the first outcome of either kind decides, use race. A{"What should a
    failure do?"} A -->|"all results required,
    any failure fails the lot"| B["Promise.all"] A -->|"report every outcome"| C["Promise.allSettled"] A -->|"first success is enough"| D["Promise.any"] A -->|"first outcome decides,
    success or failure"| E["Promise.race"]

    How to read this: start from what a partial failure should mean for the user, not from which method you remember.

    Illustration 2: the realistic example, a product page

    A product page needs three things: the product (required), reviews (optional) and recommendations (optional). The product alone decides whether the page can render, so its failure is a page error. The other two should not take the page down, so they are fetched and settled independently: allSettled fits, and each failed section shows its own "could not load" state. Wrapping all three in Promise.all would replace a complete product page with an error because a recommendations service was slow to fail. Which promises are required is a product decision the interviewer wants to hear you ask about.

    Part 2: the browser

    Q5. A fetch() returns 503. Does the catch run?

    Rule. MDN: a fetch() promise "only rejects when the request fails", for example because of a network error, and "does not reject if the server responds with HTTP status codes that indicate errors (404, 504, etc.)"; check Response.ok or Response.status.

    const r = new Response('{"message":"try later"}', { status: 503 });
    console.log(r.ok, r.status);
    console.log(await r.json());
    try { await fetch("http://127.0.0.1:1/"); } catch (e) { console.log("network failure rejects:", e.name); }
    false 503
    { message: 'try later' }
    network failure rejects: TypeError

    The Response is built locally, so this shows ok and status and that the error body parses as data; the failing request went to a port nothing listens on. Edge: the error body parses fine, so code that skips the ok check renders an error message as if it were data. The lesson on error, loading and empty states builds the full model.

    Q6. What do defer and async change for a script tag?

    Rule, from MDN's script page: a defer script is executed after the document has been parsed, before DOMContentLoaded, in document order, and delays that event until it has run. An async classic script is fetched in parallel with parsing and evaluated as soon as it is available, with no guaranteed order, and evaluation blocks rendering while it runs. MDN warns that neither attribute has an effect without src, and that defer has no effect on module scripts because they defer by default. Edge: a script that needs another script's globals cannot be async unless something orders them.

    Q7. What is the difference between event.target and event.currentTarget, and what is delegation?

    Rule, from MDN: target is the element the event was fired on; currentTarget is the element the handler is attached to. Events bubble from the innermost element outward by default; with the capture option a listener runs earlier, and capturing listeners run before target and bubbling ones. Delegation puts one listener on a parent and uses event.target to find which child was clicked, instead of one listener per child. Edge: stopPropagation() on a child stops the event reaching the parent, so a delegated handler never sees it. The lesson on DOM events and delegation covers the details.

    Part 3: React

    Q8. A handler calls setCount(count + 1) three times. What is the count after one click?

    Rule, from react.dev: state is a snapshot; "setting state only changes it for the next render", so every call in that handler reads the same count. Passing an updater, setCount(n => n + 1), queues a calculation from the previous state, and react.dev says updater functions must be pure.

    Figure 4. One click, one snapshot

    sequenceDiagram accTitle: Three setCount calls in one handler accDescr: In render 1 the count is 0. The handler calls setCount(count + 1) three times, each reading 0, so the queue holds three replace-with-1 entries and render 2 shows 1. With updater functions, each queued function receives the previous result, so render 2 shows 3. participant H as Handler (render 1, count = 0) participant Q as Update queue participant R as Render 2 H->>Q: replace with 0 + 1 H->>Q: replace with 0 + 1 H->>Q: replace with 0 + 1 Q->>R: count = 1 H->>Q: updater n => n + 1 (three times) Q->>R: 0, 1, 2, then 3

    How to read this: the first three arrows are the value form, the last two are the updater form; they are alternatives, not one handler.

    const click = () => {
      if (mode === "value") { setN(n + 1); setN(n + 1); setN(n + 1); }
      else { setN((x) => x + 1); setN((x) => x + 1); setN((x) => x + 1); }
    };
    value -> 1
    updater -> 3

    (mode, n and the harness, jsdom plus act, are around this snippet; the numbers are the text of the rendered button after one dispatched click.) Edge: react.dev also says that if you replace state after queueing an updater, setNumber(42) wins, and that React does not batch across separate intentional events such as two clicks.

    Q9. Why do lists need keys, and what is wrong with the index?

    Rule, from react.dev: keys tell React which array item each element corresponds to, so it can match them up when items move, are inserted or deleted. Keys must be unique among siblings and must not change. Of using the index, the page says it "often leads to subtle and confusing bugs", and of Math.random() keys that they make everything be recreated each render and lose user input. The page names one acceptable index case: lines that never reorder.

    Illustration 3: the failure case

    Two rows, "a" and "b", each with an uncontrolled text input. The user types into row "a", then the list is reordered to b, a.

    index keys: b:typed-in-a a:
    id keys:    b: a:typed-in-a

    With index keys, React matches by position, so the first position keeps its input, now beside the label "b": the typed text stayed behind while the row moved. With stable ids the typed text follows its row. The lesson on keys, lists and identity covers the reconciliation reasoning.

    Q10. What is useEffect for, and what does the cleanup do?

    Rule, from react.dev: useEffect synchronizes a component with an external system; if you are not doing that, you probably do not need one. After a commit with changed dependencies React runs the old cleanup, then the new setup. Dependencies are compared with Object.is; omit the array and the effect runs after every commit; an empty array runs it after the initial commit. In Strict Mode, development builds run one extra setup and cleanup cycle first, to check that cleanup mirrors setup. Related: useMemo is "only" a performance optimization, and react.dev says React may throw the cached value away, so code that is wrong without it is wrong with it.

    Trade-offs

    Answer style Strength Risk
    Rule only Fast, correct, easy to deliver Sounds memorised; the follow-up exposes it
    Rule and mechanism Shows understanding Takes time; may over-explain a simple question
    Rule, demo and edge Most convincing, checkable Needs practice; a wrong demo costs trust
    Quoting a spec or doc Authoritative Can drift from how a given engine or version behaves

    Build it

    This lesson has no lab. The snippets are small enough to run in Node 26 (node file.mjs), and the React one needs React 19 and jsdom; each question's source page tells you what to expect.

    In practice: preparing for a mixed front-end loop

    The situation

    A candidate has a loop with a JavaScript fundamentals round, a React round and a system design round. They have read a long list of questions and cannot recite it all.

    Starting architecture

    Their notes are a flat list of "Question: answer" lines copied from various sites, with no sources and no code.

    Options considered

    1. Memorise more answers. 2. Keep the list but add a runnable snippet and a source link to each. 3. Pick ten topics and be able to derive the answer from the mechanism.

    The decision

    Option 2 for breadth, with option 3 for the topics that recur in their own projects: the event loop, promises, fetch, keys, state updates and effects.

    Rollout and verification

    Each note gets a one-sentence rule, a snippet they ran, the output pasted next to it, and a link to the page that states the rule. If the output surprises them, the note is rewritten.

    The 2 a.m. failure

    The night before, they notice a remembered answer ("setState is asynchronous") disagrees with the snapshot explanation on react.dev. They fix the note to say that state is fixed within a render and updates are applied for the next one. The mistake was caught because the answer had a source.

    This is a realistic scenario, not a case history.

    Architect's notes

    • Prefer questions you can run. If a snippet cannot demonstrate it, ask whether you can name its source.
    • Say what you do not know. "I would check the spec" beats a confident guess.
    • Link the question to a design. "Why keys?" becomes "how do I keep input state in a reorderable list?"
    • Mind versions. Strict Mode behaviour and React APIs are version-dependent; name the version.

    Common mistakes

    • Reciting "let is not hoisted". MDN's TDZ description is the accurate version.
    • Saying fetch rejects on 404. It resolves; check ok.
    • Treating setTimeout(fn, 0) as immediate.
    • Using the index as a key in a list that can reorder.
    • Using useMemo for correctness.

    Key takeaways

    • A good answer is rule, mechanism, demo and edge, in that order.
    • var shares one variable across loop callbacks; let in a for header gives each iteration its own.
    • Microtasks drain before the next task; a 0 ms timer is still a later task.
    • Pick the promise combinator by what a partial failure should do.
    • fetch resolves on HTTP errors; React state is a snapshot per render; keys must be stable.

    Practice exercises

    Exercise 1: Starter (30 min). Run the Q3 snippet and add a Promise.resolve().then inside the timer callback. Predict, then check, where its output lands.

    Exercise 2: Intermediate (2 hours). For Q5, write getJson(url) that throws on !res.ok and test it with new Response(..., { status: 404 }).

    Exercise 3: Advanced (half day). For three questions in this lesson, find the matching section of the ECMAScript or HTML specification and note one thing the MDN summary leaves out.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments