What does this log, in order?
console.log('A');
setTimeout(() => console.log('B'), 0);
Promise.resolve().then(() => {
console.log('C');
setTimeout(() => console.log('D'), 0);
});
queueMicrotask(() => console.log('E'));
console.log('F');
- A. A F C E B D ✓
- B. A F C E D B
- C. A C E F B D
- D. A F E C B D
Correct answer: A. Sync runs first (A,F), then the microtask queue drains fully (C then E, since C was queued before E), and only then macrotasks in FIFO order (B, then D which was queued during the first microtask).
A senior sees this render slow. The list has 5,000 rows and a colleague immediately wraps every row in React.memo and adds useMemo everywhere. What is the correct first objection?
function Row({ item }) { return <li>{item.label}</li>; }
function List({ items }) { return <ul>{items.map(i => <Row key={i.id} item={i} />)}</ul>; }
- A. React.memo will not help because Row has no props
- B. Without profiling you don't know memo is the bottleneck; rendering 5,000 DOM nodes at once likely needs virtualization, not memoization ✓
- C. useMemo on the map result fixes it since map allocates a new array each render
- D. memo is useless in React 18 because the compiler auto-memoizes
Correct answer: B. The red flag is optimizing before measuring; a 5,000-node list is a DOM/layout cost that memoization can't fix, and the Profiler would point to virtualization instead.
This effect logs a stale count. Why, and what is the minimal correct fix?
function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const id = setInterval(() => console.log(count), 1000);
return () => clearInterval(id);
}, []);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
- A. The interval closure captured count=0 from the first render; use a ref (or functional read) so the interval reads the latest value ✓
- B. setInterval is unreliable in React; switch to setTimeout recursion
- C. Add count to the dependency array is the only acceptable fix and has no downside
- D. State updates are async so count is always one behind; add a useLayoutEffect
Correct answer: A. The empty-dep effect runs once and its closure permanently captures count=0; reading through a ref (updated each render) or adding count to deps both fix it, but only the ref avoids tearing down the interval every tick.
A CORS request from https://app.example.com sends cookies via fetch(url, { credentials: 'include' }). The server responds with Access-Control-Allow-Origin: * and Access-Control-Allow-Credentials: true. What happens?
- A. It works; * matches every origin including the credentialed one
- B. The browser blocks it: with credentials, the ACAO header must echo the specific origin, not the wildcard * ✓
- C. It works only if SameSite=None is also set on the cookie
- D. The preflight succeeds but the cookie is silently stripped from the actual request
Correct answer: B. The Fetch spec forbids the wildcard when credentials are included; the server must reflect the exact origin (and the browser rejects the response otherwise).
Predict the output:
const obj = {
val: 42,
regular() { return (function () { return this?.val; })(); },
arrow() { return (() => this.val)(); }
};
console.log(obj.regular(), obj.arrow());
- A. 42 42
- B. undefined 42 ✓
- C. 42 undefined
- D. undefined undefined
Correct answer: B. The inner regular function is called plain so its `this` is undefined (strict) giving undefined via optional chaining, while the arrow captures the method's `this` (obj) yielding 42.
Why did React's Fiber architecture replace the old stack reconciler? Pick the most fundamental reason.
- A. Fiber uses less memory by reusing a single tree
- B. Reconciliation was synchronous and uninterruptible; Fiber makes work a linked list of units that can be paused, prioritized, and resumed so high-priority updates aren't blocked ✓
- C. Fiber removed the virtual DOM entirely in favor of direct DOM diffing
- D. Fiber enables server components by moving rendering to the server
Correct answer: B. The stack reconciler recursed synchronously and couldn't be interrupted; Fiber restructures work into resumable units enabling priority scheduling and time-slicing.
A form input feels janky while filtering a huge list on each keystroke. You want the input to stay responsive and the list to update at lower priority without debouncing. Which is the idiomatic React 18 tool, and what's the caveat?
- A. useMemo on the filtered list — it will skip recomputation
- B. useDeferredValue on the filter text — the list renders with a lagging value, but the underlying filtering work must still be cheap enough or you also need virtualization ✓
- C. useCallback on the onChange handler to prevent re-renders
- D. useLayoutEffect to batch the updates synchronously
Correct answer: B. useDeferredValue lets the input update urgently while the list re-renders from a deferred value at lower priority, but it only reprioritizes—it doesn't make an expensive render cheap.
Storing a JWT in localStorage vs an httpOnly SameSite=Strict cookie: which statement is the accurate trade-off?
- A. localStorage is safe because JS on your own origin is trusted
- B. httpOnly cookies are immune to CSRF so no other defense is needed
- C. localStorage is readable by any XSS-injected script (token exfiltration), while an httpOnly cookie is not JS-readable but reintroduces CSRF risk that SameSite/anti-CSRF tokens must address ✓
- D. Both are equivalent since HTTPS encrypts the token in transit
Correct answer: C. localStorage tokens are exposed to XSS; httpOnly cookies block that read but are auto-sent by the browser, so CSRF protections become necessary.
Passing a value through React Context, this consumer re-renders on every provider render even when `user` is unchanged. What's the root cause?
<AuthContext.Provider value={{ user, login, logout }}>
- A. Context always re-renders all consumers regardless of value
- B. The value object literal is a new reference each render, so all consumers re-render; memoize it with useMemo ✓
- C. useContext doesn't support object values
- D. You must wrap consumers in React.memo — context bypasses memo, so it can't be fixed
Correct answer: B. Context compares the value by reference; a fresh object literal each render invalidates all consumers, so the provider value should be memoized (splitting stable vs volatile values also helps).
Two rapid searches: request A (for 're') is slow, request B (for 'react') is fast and arrives first. Without care the UI shows A's results last. Which is the robust fix for this out-of-order async race?
- A. Add a loading spinner so the user waits
- B. Debounce the input to 300ms — this guarantees ordering
- C. Track the latest request (e.g. an AbortController to cancel A, or an ignore flag / request id) so stale responses are discarded ✓
- D. Wrap both in Promise.all so they resolve together
Correct answer: C. Cancelling superseded requests or tagging responses with a request id and dropping any that aren't the latest prevents a slow earlier response from clobbering fresh data; debouncing reduces but doesn't eliminate the race.
Given `for (var i=0;i<3;i++){ setTimeout(()=>console.log(i),0); }`, what is logged?
- A. 0 1 2
- B. 3 3 3 ✓
- C. 0 0 0
- D. undefined three times
Correct answer: B. var is function-scoped, so all three closures share one i, which is 3 by the time the timeouts run; let would print 0 1 2.
In the browser event loop, which queue is drained completely before the next task (macrotask) runs?
- A. The animation frame queue
- B. The microtask queue (e.g., resolved Promises) ✓
- C. The render queue
- D. The timer queue
Correct answer: B. After each macrotask, the engine fully drains the microtask queue (Promise callbacks, queueMicrotask) before the next macrotask.
What does `console.log(0.1 + 0.2 === 0.3)` output and why?
- A. true, exact arithmetic
- B. false, due to IEEE-754 floating-point representation ✓
- C. true, JS rounds automatically
- D. throws a TypeError
Correct answer: B. 0.1 and 0.2 cannot be represented exactly in binary floating point, so their sum is slightly more than 0.3, making the comparison false.
A large layout thrash happens when JS repeatedly reads offsetHeight then writes styles in a loop. The core cause is:
- A. Garbage collection pauses
- B. Forced synchronous reflow because reads flush pending style/layout writes ✓
- C. Too many DOM nodes only
- D. Slow network requests
Correct answer: B. Interleaving layout reads and writes forces the browser to recompute layout synchronously each iteration; batching reads then writes avoids the thrash.
Which statement about CSS specificity is correct for `#nav .item a:hover`?
- A. Its specificity is (0,1,1,1)
- B. Its specificity is (0,1,2,1) ✓
- C. Inline styles always lose to it
- D. !important lowers its specificity
Correct answer: B. One id (1), two of class/pseudo-class (.item and :hover), and one element (a) give specificity 0,1,2,1.
In HTTP/2, what problem from HTTP/1.1 does multiplexing primarily solve?
- A. TLS handshake latency
- B. Head-of-line blocking at the application layer by allowing concurrent streams over one connection ✓
- C. DNS resolution time
- D. Cookie size limits
Correct answer: B. HTTP/2 multiplexes many streams over a single connection, removing the HTTP/1.1 head-of-line blocking where responses had to return in order per connection.
A JWT stored in localStorage is criticized as less secure than an HttpOnly cookie mainly because:
- A. It cannot be signed
- B. It is readable by JavaScript, so an XSS flaw can exfiltrate it ✓
- C. It expires immediately
- D. It cannot be sent to the server
Correct answer: B. localStorage is accessible to any JS on the page, so an XSS vulnerability can steal the token, whereas HttpOnly cookies are shielded from script access.
Which describes the difference between debouncing and throttling an event handler?
- A. They are identical techniques
- B. Debounce fires once after activity stops; throttle fires at most once per interval during activity ✓
- C. Throttle fires only after activity stops; debounce fires continuously
- D. Both fire on every event
Correct answer: B. Debounce delays execution until events stop for a quiet period; throttle guarantees the handler runs at a fixed maximum rate while events continue.
In React, why can updating state inside render cause an infinite loop, while updating it in useEffect with a proper dependency array does not?
- A. useEffect never re-runs
- B. render must be pure and side-effect-free; each render setting state schedules another render, whereas useEffect runs after commit and gates on dependencies ✓
- C. State updates in render are ignored
- D. React batches render but not effects
Correct answer: B. Rendering should be pure; calling setState during render triggers an immediate re-render loop, while useEffect runs post-commit and only re-runs when its dependencies change.
The CSS `z-index` on a positioned element seems ignored because a parent creates a stacking context. Which property does NOT create a new stacking context?
- A. opacity less than 1
- B. transform other than none
- C. position: static with no other triggers ✓
- D. will-change: transform
Correct answer: C. position: static (with no opacity/transform/filter/etc.) does not establish a stacking context; the other properties each create one, trapping child z-index values.
In JavaScript, what does the following log: for(var i=0;i<3;i++){ setTimeout(()=>console.log(i),0) }?
- A. 0 1 2
- B. 3 3 3 ✓
- C. 0 0 0
- D. undefined undefined undefined
Correct answer: B. var is function-scoped so all callbacks share one i, which is 3 after the loop finishes before the timeouts fire.
A page's Largest Contentful Paint is poor because a large hero image loads late. Which HTML hint most directly prioritizes its fetch?
- A. loading="lazy" on the image
- B. <link rel="preload" as="image"> for the hero ✓
- C. defer on all scripts
- D. display:none until loaded
Correct answer: B. Preloading the LCP image tells the browser to fetch it with high priority early, improving LCP.
What is the primary reason CORS blocks a browser fetch to a different origin even though the server received the request?
- A. The server was offline
- B. The response lacked the required Access-Control-Allow-Origin header for that origin ✓
- C. The URL used HTTPS
- D. The request used GET
Correct answer: B. CORS is enforced by the browser; without a matching Access-Control-Allow-Origin header the response is blocked from JavaScript.
In the browser event loop, which queue is drained to completion BEFORE the next macrotask (e.g., setTimeout) runs?
- A. The render queue
- B. The microtask queue (Promises) ✓
- C. The animation queue
- D. The idle callback queue
Correct answer: B. After each macrotask the engine fully drains the microtask queue (Promise callbacks) before the next macrotask.
Why can two visually identical CSS rules with 'position: sticky' behave differently, where one never sticks?
- A. sticky requires JavaScript
- B. The sticky element's nearest scrolling ancestor has overflow:hidden/auto that clips or lacks scroll range ✓
- C. sticky only works on <table>
- D. sticky needs a fixed pixel height
Correct answer: B. position:sticky depends on a scrollable ancestor; if an ancestor sets overflow that removes the scroll context, sticking fails.
What security benefit does the 'SameSite=Strict' cookie attribute provide?
- A. Encrypts the cookie value
- B. Prevents the cookie from being sent on cross-site requests, mitigating CSRF ✓
- C. Compresses the cookie
- D. Makes the cookie readable by JavaScript
Correct answer: B. SameSite=Strict stops the browser from attaching the cookie to cross-site requests, defending against CSRF.
In React, why can calling a state setter inside render without a condition cause an infinite loop?
- A. setState is asynchronous only in events
- B. Each set triggers a re-render, which calls the setter again, repeating endlessly ✓
- C. React caches renders forever
- D. It mutates the virtual DOM directly
Correct answer: B. An unconditional setState during render schedules another render that runs the same setter, creating an infinite render loop.
A CSS animation on 'top'/'left' stutters while the same motion on 'transform: translate' is smooth. Why?
- A. transform triggers layout on every frame
- B. top/left trigger layout and paint each frame; transform is composited on the GPU ✓
- C. translate uses fewer pixels
- D. top/left are deprecated
Correct answer: B. Animating top/left forces layout+paint per frame, whereas transform runs on the compositor/GPU without reflow, staying smooth.
When does the JavaScript 'this' inside a regular function called as a plain function (not a method) refer to in strict mode?
- A. The global object
- B. undefined ✓
- C. The calling function
- D. The nearest object literal
Correct answer: B. In strict mode a plain function call binds this to undefined rather than the global object.
Why might a service worker serve stale content even after you deploy a new version of the site?
- A. Service workers ignore new deploys forever
- B. The cached assets are served from the cache-first strategy until the worker updates and activates ✓
- C. HTTPS blocks updates
- D. The browser deleted the manifest
Correct answer: B. A cache-first service worker keeps serving cached assets until a new worker is fetched, installed, and activated.