JavaScript Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How does the event loop process tasks in the browser?
Correct answer: One macrotask, then the whole microtask queue, then a possible render
After each macrotask (script, event, timer), the microtask queue is drained completely, including microtasks added along the way. Then the browser may update rendering (calling
requestAnimationFrame) if it's time for a frame. That's why a long chain of microtasks also blocks rendering.2. What happens to the page?
function loop() { Promise.resolve().then(loop); } loop();Correct answer: The page freezes: microtasks are added endlessly and rendering never happens
The stack doesn't grow (each call is a separate microtask), so there's no overflow. But the microtask queue never empties, and the event loop never moves on to rendering or events. With
setTimeout(loop)the page would stay responsive.3. Does the
new Promise(executor)executor function run synchronously?new Promise(() => console.log("A")); console.log("B");Correct answer: Yes:
Ais printed, thenBThe executor is called right away in the constructor. Only
then/catch/finallycallbacks are asynchronous - they always run as microtasks, even if the promise is already settled. This guarantees a predictable code order.4. Why will the promise below never reject?
new Promise((resolve, reject) => { setTimeout(() => { throw new Error("boom"); }, 0); });Correct answer: The exception in the timer is thrown outside the executor and isn't tied to the promise
Only synchronous exceptions in the executor automatically become rejections. An error in a timer callback happens later, in a separate task: it becomes a global unhandled error, and the promise stays
pendingforever. You need to callrejectexplicitly.5. How do you globally track unhandled promise rejections in the browser?
Correct answer: The
unhandledrejectionevent onwindowwindow.addEventListener('unhandledrejection', e => report(e.reason))is the standard way to send such errors to monitoring. Synchronous unhandled errors are caught by theerrorevent onwindow. There's noPromise.onErrormethod.6. What does
for await...ofdo?Correct answer: Iterates over an async iterable, awaiting each value
It works with objects that have
Symbol.asyncIterator: async generators, streams (ReadableStream), API pagination. Iterations run sequentially. To process an array of promises in parallel, usePromise.all.7. What is an async generator handy for?
async function* pages(url) { while (url) { const res = await fetch(url).then(r => r.json()); yield res.items; url = res.next; } }Correct answer: For lazily yielding data in chunks that arrive asynchronously
The consumer writes
for await (const items of pages(url))and decides when to stop - the next page isn't requested until it's needed. Leaving the loop withbreakcalls the generator'sreturn()and finishes it.8. What is
Proxyused for?Correct answer: To intercept operations on an object: reads, writes, deletions
Traps such as
get,set,hasanddeletePropertylet you implement reactivity (that's how Vue 3 works), validation, logging and default values.Reflectprovides the default behavior of operations for use inside traps.9. What conditions guarantee that the garbage collector will remove an object?
Correct answer: The object is unreachable from the roots (globals, the stack, closures)
Modern engines use mark-and-sweep: everything reachable from the roots is alive. Circular references between unreachable objects don't prevent their removal - unlike reference counting. The timing of collection is unspecified.
10. Which scenario typically causes a memory leak in an SPA?
Correct answer: Handlers on
windowand timers that aren't removed when leaving the pageA subscription holds a closure, and through it the component's data and DOM nodes. Other sources: detached DOM nodes referenced from JS, growing global caches, forgotten
setIntervals. Short-lived objects are efficiently collected by the GC's young generation. Leaks are found with Memory snapshots in DevTools.11. Why are you advised to be careful with
WeakRefandFinalizationRegistry?Correct answer: Garbage collection timing is unpredictable - logic shouldn't depend on it
An object behind a
WeakRefcan disappear at any moment or live longer than expected, and a finalization callback may never be called. They're appropriate for caches and as a safety net, but not for mandatory resource cleanup.12. What doesn't code inside a Web Worker have?
Correct answer: Access to the DOM; it talks to the main thread via
postMessageA worker runs in a separate thread, so heavy computations don't block the UI.
fetch, timers, IndexedDB and modules (type: 'module') are available. Data is passed by copying (structured clone) or by transferring ownership (Transferable, e.g.ArrayBuffer).13. Why pass an
ArrayBufferto a worker as transferable:postMessage(buf, [buf])?Correct answer: Ownership moves without copying, emptying the source buffer
Copying large data is expensive. A transfer hands over the memory instantly, and the sender's
byteLengthbecomes 0. True shared memory isSharedArrayBufferwithAtomics, but it requires cross-origin isolation (COOP/COEP headers).14. What can a Service Worker do?
Correct answer: Intercept the page's network requests and respond from cache, working offline
A Service Worker is a proxy between the page and the network with its own lifecycle (
install,activate,fetch). PWAs are built on it: caching strategies (cache-first, network-first, stale-while-revalidate), push notifications, background sync. It works only over HTTPS and can't see the DOM.15. How do Server-Sent Events differ from WebSocket?
Correct answer: SSE is a one-way stream from the server over HTTP, WebSocket a two-way channel
SSE (
EventSource) is simpler: plain HTTP, automatic reconnection, text events - enough for notifications and streaming responses. WebSocket is needed for frequent two-way exchange (chats, games, collaborative editing) and supports binary data.16. What must you check in a
messagehandler when talking to an iframe viapostMessage?Correct answer:
event.origin- that the message came from the expected domainpostMessageworks across origins, and any window can send a message. Without checkingorigin, an attacker can send forged commands. When sending, specify a concretetargetOrigininstead of'*'. Between tabs of the same site,BroadcastChannelis handy.17. How do you implement the observer pattern with browser APIs, without libraries?
Correct answer: With
EventTargetandCustomEvent:dispatchEventandaddEventListenerYou can extend a class from
EventTargetand dispatchnew CustomEvent('change', { detail }). Other built-in observers:MutationObserver(DOM changes),IntersectionObserver,ResizeObserver.Object.observewas removed from the standard.18. Why is
ResizeObserverbetter than awindow.resizehandler for a component?Correct answer: It reports size changes of a specific element for any reason
An element can change size without the window changing: a sidebar opened, content loaded.
ResizeObservertracks the element itself and is called in the rendering cycle, without pollinggetBoundingClientRect. Useful for charts and virtualized lists.19. What does a tagged template do?
const q = sql`SELECT * FROM users WHERE id = ${id}`;Correct answer: Calls the
sqlfunction with an array of string parts and the substituted valuesThe tag function receives
stringsand the values separately, so it can safely escape substitutions or pass them as query parameters - protection against injections. That's how styled-components,graphqltags andString.rawwork.20. In what order will
Object.keysreturn the keys of{ b: 1, 2: 1, a: 1, 1: 1 }?Correct answer:
['1', '2', 'b', 'a']Integer keys come first in ascending order, then string keys in insertion order, then symbols (which
Object.keysdoesn't return). If order matters for numeric keys, use aMap.21. How do you deep-freeze an object?
function deepFreeze(obj) { for (const value of Object.values(obj)) { if (value && typeof value === "object") deepFreeze(value); } return Object.freeze(obj); }Correct answer: Recursively freeze nested objects, then the object itself
Object.freezeis shallow, andObject.sealonly prevents adding and removing properties. Recursion walks the tree; for circular references, keep visited objects in aWeakSet.freezehas nodeepoption.22. How do you serialize an object with circular references to JSON?
Correct answer: Via a
replacerinJSON.stringify, tracking visited objects in aWeakSetJSON.stringifythrowsTypeError: Converting circular structure to JSON. In areplaceryou can skip already-seen objects or replace them with a marker reference (as libraries like flatted do). For copying within JS,structuredCloneworks - it supports cycles.23. How do you limit the number of concurrent requests when loading 100 URLs?
Correct answer: A pool: N "workers" take URLs from a shared queue until it's empty
Promise.allstarts everything at once and has no limit (the browser's connection limit concerns the network, not memory or the server). A pool of N async functions pulling tasks from a queue keeps exactly N requests in flight. Ready-made implementations:p-limitand similar.24. What is exponential backoff when retrying requests?
Correct answer: Increasing the pause between attempts (1s, 2s, 4s…), often with random jitter
A growing delay reduces load on an overloaded server, and jitter (a random addition) keeps all clients from retrying in sync. Only retry idempotent operations and transient errors (5xx, network), not 4xx.
25. Why is it important to preserve
thisand arguments in a debounce implementation?function debounce(fn, ms) { let t; return function (...args) { clearTimeout(t); t = setTimeout(() => fn.apply(this, args), ms); }; }Correct answer: Otherwise the wrapped method loses the object's context and call parameters
The wrapper must be transparent: calling
obj.save(data)through debounce has to reachfnwith the samethisand arguments. That's why a regular function is returned (it has its ownthis), and inside the timer an arrow preserves it.26. Why can adding properties to objects in different orders slow code down in V8?
Correct answer: The objects get different hidden classes and optimize worse
The engine optimizes property access by the object's "shape" (hidden class / shape). If objects of one type are created with different orders or sets of fields, the call site sees many shapes and loses the fast path. Initialize all fields in the constructor right away and don't remove them with
delete.27. How do you avoid blocking the UI when processing 100,000 items on the main thread?
Correct answer: Split the work into chunks and yield the thread (or move it to a worker)
Tasks longer than 50 ms hurt responsiveness (INP).
asyncdoesn't create a new thread: a synchronous loop inside still blocks. Cut the work into pieces and yield viasetTimeout,scheduler.yield()(where supported) orrequestIdleCallback; move heavy computation to a Web Worker.28. Why is
performance.now()better thanDate.now()for measuring execution time?Correct answer: It's a precise monotonic timer independent of the system clock
Date.now()is milliseconds by the system clock, which can shift (sync, time changes).performance.now()counts from the start of navigation with fractional milliseconds. For marks in DevTools there areperformance.mark()andmeasure().29. What does
new Date(2025, 1, 1).getMonth()return, and which month is it?Correct answer:
1- FebruaryMonths in
Dateare zero-based, while days start at one. It's a common source of bugs along with time zones andDatemutability. UseIntl.DateTimeFormatfor formatting; theTemporalAPI is replacingDate.30. What happens with
10n + 1?Correct answer:
TypeError: you can't mixBigIntandNumberin arithmeticImplicit mixing is forbidden to avoid losing precision. Be explicit:
10n + BigInt(1)orNumber(10n) + 1.BigIntis needed for integers larger thanNumber.MAX_SAFE_INTEGER(2^53 − 1): IDs, cryptography.JSON.stringifydoesn't support it.31. Why does
9007199254740993 === 9007199254740992returntrue?Correct answer: Numbers above
MAX_SAFE_INTEGERcan't be represented exactlyA double has a 53-bit mantissa, so not all integers beyond 2^53 are representable. Large IDs from APIs (e.g. 64-bit ones) come in JSON as strings or are handled via
BigInt, otherwise they're silently corrupted. Check withNumber.isSafeInteger.32. What is ReDoS?
Correct answer: Denial of service caused by a "heavy" regular expression
Expressions like
/^(a+)+$/on a specially crafted string take exponential time and block the thread (especially dangerous on a Node.js server). Avoid nested quantifiers, limit input length, use safe engines.33. What's dangerous about a deep-merge function applied to user-supplied JSON?
merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));Correct answer: Prototype pollution: the property ends up in
Object.prototypeA naive merge assigns
target.__proto__.isAdmin = true, and({}).isAdminbecomestrueacross the whole app. Protection: skip__proto__,constructor,prototype, useObject.create(null)orMapfor dictionaries, validate input with a schema.34. Why are
evalandnew Functionusually banned by security policy?Correct answer: They execute strings as code - a path to XSS
If user data ends up in the string, an attacker runs their own code. CSP blocks such calls by default. Also,
evalhinders engine optimizations. There's almost always an alternative:JSON.parse, a function table,Functionwith code known at build time.35. What can happen with a circular dependency between ES modules?
// a.js import { b } from "./b.js"; export const a = "A" + b; // b.js import { a } from "./a.js"; export const b = "B" + a;Correct answer:
ReferenceError: accessing aconstbefore initializationModules execute in graph order; with a cycle, one of them starts running while the other's export is still in the TDZ. With
varyou'd getundefined; withconst/let/classes, an error. The fix is to move shared code into a third module or access the import lazily inside functions.36. How does top-level
awaitin a module affect the modules that import it?Correct answer: Their execution waits until the module with
awaitfinishes initializingA module with top-level
awaitbecomes an async node of the graph, and dependent modules run after it. Handy for loading configuration, but a slowawaitdelays the whole branch of the app.37. What does
Promise.withResolvers()(ES2024) give you?Correct answer: Returns
{ promise, resolve, reject }for control from outsidePreviously you wrote a "deferred" for this: declared variables and assigned
resolve/rejectinside the constructor. Handy when a promise is resolved from elsewhere - for example, from an event handler or a queue.38. What does
new Set([1, 2, 3]).intersection(new Set([2, 3, 4]))return?Correct answer:
Set {2, 3}Since 2024,
Sethas set-theory methods:union,intersection,difference,symmetricDifference,isSubsetOfand more. Previously this was written by hand withfilter. Check target browser support before using it in production.39. What does
Object.groupBy(users, u => u.role)do?Correct answer: Returns an object: key - role, value - array of users
Object.groupBy(ES2024) replaces the typicalreducefor grouping. The result is an object with anullprototype. If keys aren't strings, useMap.groupBy.40. What is
MutationObserveruseful for?Correct answer: It asynchronously reports DOM changes
For example, to react to markup inserted by a third-party widget or to implement autosave for
contenteditable. Change records arrive in a batch as a microtask. For JS objects useProxy; forlocalStorage, thestorageevent.41. Where should you store large structured data on the client (e.g. an offline cache)?
Correct answer: In IndexedDB - an async database with indexes and a large quota
localStorageis limited to a few megabytes, stores only strings and blocks the thread. Cookies are small (~4 KB) and are sent with every request. IndexedDB stores objects andBlobs and supports transactions and indexes; it's easier to use via wrappers likeidb.42. How do you sync data between tabs of the same site?
Correct answer: With
BroadcastChannelor thestorageeventBroadcastChannel('app')delivers messages to all contexts of the same origin (tabs, iframes, workers). Thestorageevent fires in other tabs whenlocalStorageis written.sessionStorageis isolated per tab.43. Why cache
Intl.NumberFormatinstances?Correct answer: Creating a formatter is expensive, while calling it is cheap
Intlconstructors load locale data and parse options. CallingtoLocaleString()in a loop over thousands of rows creates a formatter every time. Better to createnew Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })once and callformat.44. What's the right way to build a query string from a params object?
Correct answer: With
new URLSearchParams(params).toString()URLSearchParamscorrectly encodes spaces, non-ASCII characters and special characters like&, which would break the request or allow parameter tampering with manual concatenation. TheURLobject lets you work with the whole address:url.searchParams.set('page', 2).45. What does the expression return?
const obj = { [Symbol.toPrimitive](hint) { return hint === "number" ? 42 : "obj"; }, }; console.log(+obj, `${obj}`);Correct answer:
42 objWhen converting to a primitive, the engine calls
Symbol.toPrimitivewith the hint'number','string'or'default'. Without it,valueOfandtoStringare used. This is how, for example, date subtraction works:date2 - date1.46. What does
[1, 2, 3, 4].findLast(n => n % 2 === 1)return?Correct answer:
3findLastandfindLastIndex(ES2023) search from the end of the array - withoutreverse, which mutates the array. For multiple matches, usefilter.47. Why pass the
causeoption toError?try { await save(); } catch (err) { throw new Error("Failed to save the order", { cause: err }); }Correct answer: To keep the original error and not lose the root cause
Wrapping errors adds application-level context, and
causekeeps the low-level error with its stack. DevTools and many monitoring systems show the whole chain of causes.48. What is the Temporal Dead Zone for default parameters?
function f(a = b, b = 1) { return a; } f();Correct answer:
ReferenceError: parameterbisn't initialized yet whenais evaluatedParameters are initialized left to right and behave like
let: accessing a not-yet-initialized parameter is a TDZ error. In the reverse order (a = 1, b = a) it works. Default values are evaluated on every call, not once.49. What is
globalThisuseful for?Correct answer: Uniform access to the global object in any environment
In the browser the global object is
window, in workersself, in Node.jsglobal.globalThisworks everywhere, which matters for universal (isomorphic) code and libraries.50. Why shouldn't you pass an
asyncfunction as the executor innew Promise(async (resolve) => ...)?Correct answer: An error after
awaitwon't reject the promise - it hangsThe constructor ignores the promise returned by an async executor, so an exception after
awaitbecomes an unhandled rejection, and the outer promise stayspending. If there's already anawaitinside, thenew Promisewrapper usually isn't needed at all - an async function is enough.51. How do you abort a
fetchafter 5 seconds or when the user navigates away, whichever comes first?const signal = AbortSignal.any([AbortSignal.timeout(5000), controller.signal]); await fetch(url, { signal });Correct answer: Merge
AbortSignal.timeout()and a controller's signal withany()fetchhas no timeout option.AbortSignal.timeoutrejects with aTimeoutError, while a manual abort gives anAbortError, so you can tell them apart.52. What do iterator helpers like
map.values().filter(...).take(3)give you?Correct answer: Lazy, chainable operations on any iterator
Iterator.prototypegainedmap,filter,take,drop,flatMap,reduce,toArrayand more. They process items on demand, sotake(3)on a huge or infinite generator stops early.53. What problem does
Promise.try(fn)solve?Correct answer: It turns sync throws and async rejections into a rejected promise
Promise.resolve().then(fn)delays execution to a microtask, andnew Promise(r => r(fn()))is verbose.Promise.tryruns synchronously but still gives uniform error handling.54. What does this regex give you?
const { groups } = /(?<year>\d{4})-(?<month>\d{2})/.exec("2025-07"); console.log(groups.month);Correct answer:
"07"- named groups work by nameNamed groups make regexes self-documenting and robust to reordering. In
replaceyou reference them as$<month>.55. What does
Promise.anyreject with when all promises reject?Correct answer: An
AggregateErrorwith all rejection reasonsSince it waits for the first success, failure means "everything failed", so all reasons are kept. Check
err instanceof AggregateErrorto log them.56. What must a page do to use
SharedArrayBuffer?Correct answer: Be cross-origin isolated with COOP and COEP headers
After Spectre, shared memory and high-resolution timers were restricted. Isolation can break third-party embeds that don't send CORP/CORS headers.
57. When is
requestIdleCallbackappropriate?Correct answer: For low-priority work that can wait until the browser is idle
The callback gets a deadline (
timeRemaining()); do small chunks and reschedule. Passtimeoutto guarantee it runs eventually on busy pages.58. Why might a bundler fail to tree-shake an unused export from a library?
Correct answer: The code isn't ESM, or the module may have side effects
Static
import/exportlets bundlers prove a binding is unused. CommonJSrequireand top-level side effects (polyfills, global registration) force the module to be kept.59. Why can this code freeze the page even though it uses promises?
function loop() { Promise.resolve().then(loop); } loop();Correct answer: Each microtask schedules another, so rendering never happens
The browser renders only between macrotasks after the microtask queue drains. Use
setTimeout,MessageChannelorscheduler.yield()to give rendering a chance.60. What does
Object.is(-0, 0)return, and why does it exist?Correct answer:
false- it tells-0from+0React and other libraries use
Object.isto compare state.===says-0 === 0andNaN !== NaN.61. What does
Symbol.toPrimitivecontrol?const price = { [Symbol.toPrimitive](hint) { return hint === "number" ? 42 : "$42"; }, };Correct answer: How the object converts to a primitive
The hint is
"number","string"or"default". Without it, JS callsvalueOfandtoStringin an order depending on the hint.62. What does
[] + {}evaluate to?Correct answer:
"[object Object]"+converts both operands to primitives:[]becomes""and{}becomes"[object Object]", then strings are concatenated. Such coercions are why linters warn about mixed-type+.63. Why use
Reflect.get(target, key, receiver)inside aProxygettrap?Correct answer: It keeps the correct
receiver, so getters see the proxy asthisReturning
target[key]calls getters withthis === target, bypassing the proxy (and its tracking). Vue's reactivity usesReflectfor this reason.64. Why do schedulers (e.g. React's) use
MessageChannelinstead ofsetTimeout(fn, 0)?Correct answer: A message schedules a macrotask without timer clamping
Nested
setTimeoutcalls are clamped to at least 4ms by the HTML spec. A message event yields to the browser for rendering and input, then continues quickly.65. How do CSP nonces allow specific inline scripts?
Content-Security-Policy: script-src 'nonce-r4nd0m' <script nonce="r4nd0m">...</script>Correct answer: Only scripts with the response's random nonce run
The nonce must be unpredictable and regenerated on every response, which makes pages dynamic.
'strict-dynamic'lets trusted scripts load further scripts.66. What do Trusted Types enforce?
Correct answer: Sinks like
innerHTMLaccept only values from an approved policyEnabled via CSP
require-trusted-types-for 'script', they turn DOM XSS into a reviewable set of policies. Frameworks like Angular support them.67. How does
SameSite=Laxon a session cookie help against CSRF?Correct answer: The cookie is sent cross-site only on top-level GET navigations
Browsers default to
Laxwhen unspecified.Strictalso blocks cross-site navigations;NonerequiresSecure. CSRF tokens are still advised for sensitive actions.68. What does the
integrityattribute on a CDN<script>protect against?<script src="https://cdn.example/lib.js" integrity="sha384-..." crossorigin="anonymous"></script>Correct answer: Running a file that was modified on the CDN
Subresource Integrity requires a fixed file version; hashes break with "latest" URLs.
crossoriginis needed so the browser can read the response to verify it.69. What is
new URL("./worker.js", import.meta.url)used for?Correct answer: Resolving a file relative to the current module
Relative URLs in
fetchornew Workerresolve against the page, not the module.import.meta.urlgives the module's own URL.70. What does
<script type="importmap">enable?<script type="importmap"> { "imports": { "lodash": "https://cdn.example/lodash-es.js" } } </script>Correct answer: Bare specifiers like
import "lodash"without a bundlerImport maps map names to URLs and can also scope versions. They are used for no-build setups and micro-frontends sharing dependencies.
71. How do you sort names correctly for a given language?
const collator = new Intl.Collator("uk", { sensitivity: "base" }); names.sort(collator.compare);Correct answer: With
Intl.Collator, which follows the language's rulesDefault sort compares UTF-16 code units, so "Ä", "ї" or uppercase letters end up in wrong places.
numeric: truealso sorts "item2" before "item10".72. Why use
Intl.PluralRulesfor messages like "5 files"?Correct answer: Languages have different plural categories, and it picks the right one
new Intl.PluralRules("uk").select(5)returns"many", while English only distinguishesone/other. i18n libraries build on it.73. What is a robust way to store and transfer dates?
Correct answer: As UTC instants, converting to local time only for display
Local strings lose the time zone and break around DST changes.
Intl.DateTimeFormatwithtimeZoneformats for display; the Temporal API adds explicit time-zone-aware types.74. What does a
toJSONmethod on an object do?class Money { constructor(cents) { this.cents = cents; } toJSON() { return (this.cents / 100).toFixed(2); } } JSON.stringify({ price: new Money(1999) });Correct answer:
JSON.stringifyuses its return value instead of the objectDateusestoJSONto output ISO strings. For parsing back, pass a reviver toJSON.parse- classes aren't restored automatically.75. Is
Array.prototype.sortstable in modern engines?Correct answer: Yes, equal elements keep their order since ES2019
Stability enables multi-key sorting: sort by name, then by department, and people within a department stay alphabetical.