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
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
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
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
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
- 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 "
letis not hoisted". MDN's TDZ description is the accurate version. - Saying
fetchrejects on 404. It resolves; checkok. - Treating
setTimeout(fn, 0)as immediate. - Using the index as a key in a list that can reorder.
- Using
useMemofor correctness.
Key takeaways
- A good answer is rule, mechanism, demo and edge, in that order.
varshares one variable across loop callbacks;letin aforheader 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.
fetchresolves 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.
Related reading
In this course:
- The Event Loop and the Main Thread: the full model behind Q3.
- React Reconciliation and the Virtual DOM: why keys matter.
- React Keys, Lists and Identity: Q9 in depth.
- React Effects and Synchronization: Q10 in depth.
- DOM Events and Delegation: Q7 in depth.
- Error, Loading and Empty States: what to do with the answer to Q5.
- Request Cancellation, Retries and Timeouts: cancelling what
raceleaves running.