Consider this code:
```js
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => console.log('C')).then(() => console.log('D'));
queueMicrotask(() => console.log('E'));
console.log('F');
```
What is the exact console output order?
- A. A F C E D B ✓
- B. A F B C E D
- C. A F C D E B
- D. A F E C D B
Correct answer: A. Synchronous logs (A, F) run first, then all microtasks in enqueue order (C and E queued before D, which is chained after C), then the setTimeout macrotask (B).
A component list re-renders every item on each parent update despite `React.memo` on the child. The parent passes `onSelect={() => handle(id)}` and `style={{ margin: 4 }}` as props. Why does memo fail, and what is the minimal correct fix?
- A. memo does a deep comparison that is too slow; switch to useMemo on the whole list
- B. The inline arrow and object literal create new references each render, breaking memo's shallow prop check; memoize the callback with useCallback and hoist/memoize the style object ✓
- C. React.memo only works on class components; convert children to PureComponent
- D. memo ignores function props by design; wrap the child in useTransition
Correct answer: B. React.memo does a shallow reference comparison, and new inline function/object literals produce fresh references every render, so stabilizing them with useCallback and a memoized/constant style restores memoization.
You implement a trailing-edge debounce. A user types 5 characters within the wait window, then stops. With a correct trailing-only debounce (wait=300ms), how many times does the wrapped function execute and with which argument?
- A. 5 times, once per keystroke
- B. 1 time, with the argument from the last (5th) call ✓
- C. 1 time, with the argument from the first call
- D. 2 times: once leading, once trailing
Correct answer: B. A trailing debounce resets its timer on every call and only fires once after activity stops, invoking the function with the most recent arguments captured at the last call.
This custom hook has a bug:
```js
function useInterval(callback, delay) {
useEffect(() => {
const id = setInterval(() => callback(), delay);
return () => clearInterval(id);
}, [delay]);
}
```
What happens and why?
- A. It leaks intervals because the cleanup never runs
- B. The interval always invokes the callback captured on the first render with the delay, causing a stale-closure bug because callback is not in the deps and not stored in a ref ✓
- C. It throws because callback is a function and cannot be a dependency
- D. It re-creates the interval on every render, causing excessive timers
Correct answer: B. Because `callback` is omitted from the dependency array, the interval closes over the first render's callback and keeps calling that stale version; the standard fix stores callback in a ref updated each render.
In React 18 concurrent rendering, you wrap a state update that filters a large list in `startTransition`, while the text input's own `setState` stays outside it. What behavior does this specifically produce?
- A. The input update is delayed so both stay in sync
- B. The urgent input update stays responsive and can interrupt/preempt the in-progress non-urgent list render, which React may throw away and restart ✓
- C. Both updates are batched into a single synchronous commit
- D. The list update runs on a Web Worker off the main thread
Correct answer: B. Transitions mark the list update as interruptible/non-urgent, so a higher-priority input update can preempt the in-progress render, keeping typing responsive while React discards and restarts the stale transition render.
Predict the output:
```js
const obj = {
val: 42,
getVal: function () { return (() => this.val)(); },
getValBad: function () { return function () { return this.val; }(); }
};
console.log(obj.getVal());
console.log(obj.getValBad());
```
(non-strict mode)
- A. 42 then 42
- B. 42 then undefined ✓
- C. undefined then undefined
- D. 42 then throws TypeError
Correct answer: B. The arrow function lexically inherits `this` from getVal (obj), returning 42, while the plain IIFE is called as a standalone function so its `this` is the global object, whose `val` is undefined.
For an image-heavy product landing page, LCP is 4.1s. The LCP element is a hero `<img>` loaded via a JS component after hydration. Which single change most directly improves LCP?
- A. Add `loading="lazy"` to the hero image
- B. Server-render the hero `<img>` in the initial HTML with `fetchpriority="high"` and a preload, so it isn't blocked on JS/hydration ✓
- C. Convert the whole page to client-side rendering to reduce TTFB
- D. Wrap the hero component in React.lazy and Suspense
Correct answer: B. LCP is delayed because the largest element is discovered only after JS runs; emitting the image in the initial HTML with high fetch priority/preload lets the browser start the download immediately during the critical rendering path.
Two independently deployed micro-frontends via Webpack Module Federation both list React as a shared singleton but pin different minor versions. At runtime a hook throws "Invalid hook call." What is the root cause?
- A. Module Federation cannot share React at all
- B. With `singleton: true` but incompatible `requiredVersion` ranges, two React copies get loaded, so components and the reconciler use different React instances/dispatchers ✓
- C. React hooks are globally disabled in federated modules
- D. The shell must re-export React from a CDN for singletons to work
Correct answer: B. A hook call needs one React instance; when version ranges don't satisfy the singleton constraint, Webpack loads a second React copy, splitting the internal dispatcher and triggering the invalid-hook-call error.
What does this TypeScript evaluate `T` to?
```ts
type Unwrap<T> = T extends Promise<infer U> ? Unwrap<U> : T;
type T = Unwrap<Promise<Promise<string>>>;
```
- A. Promise<string>
- B. Promise<Promise<string>>
- C. string ✓
- D. unknown
Correct answer: C. The conditional type recursively unwraps nested Promises using `infer`, so both Promise layers are stripped, leaving `string`.
With TanStack Query, you do an optimistic update in `onMutate`, then the mutation fails on the server. To correctly restore prior UI, what must `onMutate`/`onError` do?
- A. Nothing; React Query auto-rolls back all optimistic writes
- B. In onMutate, cancel in-flight queries, snapshot the previous cache value, and write the optimistic value; in onError, restore that snapshot; then invalidate in onSettled ✓
- C. Call queryClient.clear() in onError to wipe stale data
- D. Set staleTime to 0 so the failed value auto-corrects on next render
Correct answer: B. React Query does not auto-rollback manual cache writes; the correct pattern cancels outgoing refetches, snapshots the previous value for restoration on error, and revalidates on settle.
In what order do synchronous code, a `Promise.then` callback, and a `setTimeout(fn, 0)` callback execute?
- A. synchronous, setTimeout, then
- B. synchronous, then, setTimeout ✓
- C. then, synchronous, setTimeout
- D. setTimeout, then, synchronous
Correct answer: B. Sync code runs first, then the microtask queue (Promise) drains before the macrotask (setTimeout).
Which of the following creates a new CSS stacking context?
- A. Setting `position: relative` with no z-index
- B. Setting `opacity` to a value less than 1 ✓
- C. Setting `display: block`
- D. Setting `margin: auto`
Correct answer: B. An `opacity` below 1 establishes a new stacking context, unlike `position: relative` alone.
What does the Temporal Dead Zone (TDZ) describe?
- A. The span where a let/const binding exists but cannot be accessed before its declaration ✓
- B. The time before a `var` is hoisted
- C. The gap between two event-loop ticks
- D. The delay before a Promise resolves
Correct answer: A. The TDZ is the region from block start until a let/const declaration, where accessing it throws.
What causes 'layout thrashing' in the browser?
- A. Interleaving DOM reads (e.g. offsetHeight) with writes, forcing repeated synchronous reflows ✓
- B. Declaring too many CSS classes
- C. Loading many large images
- D. Attaching many passive event listeners
Correct answer: A. Reading layout properties after writes repeatedly invalidates and recomputes layout, thrashing performance.
Inside a regular (non-arrow) function invoked as a plain function call in non-strict mode, what is `this`?
- A. undefined
- B. The global object (window) ✓
- C. The function object itself
- D. The nearest enclosing object
Correct answer: B. In non-strict mode a plain function call sets `this` to the global object; strict mode makes it undefined.
In the CSS cascade, which declaration wins over the others?
- A. A plain inline style attribute
- B. A stylesheet rule marked `!important` ✓
- C. An ID selector in the stylesheet
- D. A user-agent default rule
Correct answer: B. An `!important` declaration overrides normal declarations, including a plain inline style.
Why does batching visual updates inside `requestAnimationFrame` improve rendering performance?
- A. It aligns DOM updates with the browser's paint cycle, avoiding wasted intermediate layout work ✓
- B. It moves the work onto a Web Worker thread
- C. It permanently caches the computed layout
- D. It disables reflow for the element
Correct answer: A. rAF schedules work right before paint, so multiple updates coalesce into one frame instead of many reflows.
When you access `obj.toString()` and `obj` has no own `toString`, how does JavaScript resolve it?
- A. It walks the prototype chain until it finds the property or reaches null ✓
- B. It checks only the object's own properties
- C. It searches the global scope
- D. It inspects the constructor's arguments
Correct answer: A. Property lookup traverses the prototype chain via [[Prototype]] until the property or null is reached.
Which of these is render-blocking by default and delays the first paint?
- A. A stylesheet loaded via <link> in the <head> ✓
- B. An image referenced inside CSS
- C. A script with the `async` attribute
- D. A font declared with `rel="preload"`
Correct answer: A. External CSS in the head is render-blocking because the browser needs the CSSOM before painting.
What is a common cause of memory leaks in long-running single-page apps?
- A. Detached DOM nodes still referenced by JavaScript closures ✓
- B. Using `const` instead of `let`
- C. Running many CSS keyframe animations
- D. Receiving large JSON responses
Correct answer: A. DOM nodes removed from the tree but still referenced by JS cannot be garbage collected, leaking memory.
What does the CSS property will-change: transform primarily do?
- A. Immediately animates the transform
- B. Hints the browser to promote the element onto its own compositor layer for optimization ✓
- C. Disables all transforms on the element
- D. Forces an immediate synchronous reflow
Correct answer: B. will-change tells the browser to prepare optimizations, typically by promoting the element to a compositor layer.
In the browser event loop, how are microtasks (e.g. Promise callbacks) scheduled relative to macrotasks (e.g. setTimeout)?
- A. Macrotasks always run before microtasks
- B. The microtask queue is fully drained after each macrotask, before the next macrotask runs ✓
- C. They alternate strictly one-to-one
- D. Microtasks run only after every macrotask is exhausted
Correct answer: B. After each macrotask the engine drains the entire microtask queue before picking up the next macrotask.
What most directly causes 'layout thrashing'?
- A. Using too many CSS classes
- B. Loading large images
- C. Repeatedly interleaving DOM reads (like offsetHeight) and writes, forcing multiple synchronous reflows ✓
- D. Using inline styles instead of stylesheets
Correct answer: C. Reading a layout property after a write forces a synchronous reflow; doing this in a loop causes thrashing.
What does a JavaScript closure capture from its enclosing scope?
- A. A copy of each variable's value at creation time
- B. A reference to the variable binding, so later mutations are visible ✓
- C. Only primitive values, never objects
- D. Nothing; closures do not retain outer variables
Correct answer: B. Closures hold a live reference to the variable binding, so changes made after creation are observable.
What is the effect of the defer attribute on a <script> tag?
- A. Executes the script immediately, blocking HTML parsing
- B. Downloads in parallel and executes after HTML parsing completes, preserving document order ✓
- C. Downloads and executes as soon as available, out of order
- D. Prevents the script from loading at all
Correct answer: B. defer lets the script download without blocking parsing and runs it in order after the document is parsed.
Which selector has the highest CSS specificity?
- A. #id ✓
- B. two chained classes (.a.b)
- C. three type selectors (div p span)
- D. the :hover pseudo-class
Correct answer: A. An id selector scores (1,0,0), outranking any combination of class or type selectors.
What problem does React's useCallback hook solve?
- A. It caches an expensive computed value
- B. It returns a memoized function reference that stays stable across renders to avoid needless child re-renders ✓
- C. It replaces useEffect for side effects
- D. It stores and updates component state
Correct answer: B. useCallback memoizes a function identity so referential-equality-sensitive children do not re-render unnecessarily.
What best describes a CSS 'stacking context'?
- A. The order in which stylesheets are loaded
- B. A z-axis ordering context, created by properties such as position with z-index or opacity below 1 ✓
- C. The cascade order determined by specificity
- D. The source order of elements in the HTML
Correct answer: B. A stacking context governs how descendants are painted along the z-axis and is formed by triggers like z-index or opacity < 1.
Why can for...in be problematic when iterating over an array?
- A. It is always slower than for...of
- B. It iterates enumerable property keys including inherited ones and yields string indices, not just elements ✓
- C. It cannot access array element values
- D. It only ever visits the first element
Correct answer: B. for...in walks enumerable keys (including inherited ones) as strings, which is unsuited to ordered array element iteration.
What does the CSS containment value contain: layout enable?
- A. Wrapping of overflowing text
- B. Isolation of the element's internal layout so internal changes don't affect the outside document layout ✓
- C. Automatic centering of the element
- D. Blocking the element from being styled
Correct answer: B. contain: layout isolates layout so recalculations inside the element don't trigger reflow of the rest of the page.