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.

Quick reference: Key concepts and pitfalls on a couple of pages →
  1. 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. 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. 3. Does the new Promise(executor) executor function run synchronously?

    new Promise(() => console.log("A"));
    console.log("B");

    Correct answer: Yes: A is printed, then B

    The executor is called right away in the constructor. Only then/catch/finally callbacks are asynchronous - they always run as microtasks, even if the promise is already settled. This guarantees a predictable code order.

  4. 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 pending forever. You need to call reject explicitly.

  5. 5. How do you globally track unhandled promise rejections in the browser?

    Correct answer: The unhandledrejection event on window

    window.addEventListener('unhandledrejection', e => report(e.reason)) is the standard way to send such errors to monitoring. Synchronous unhandled errors are caught by the error event on window. There's no Promise.onError method.

  6. 6. What does for await...of do?

    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, use Promise.all.

  7. 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 with break calls the generator's return() and finishes it.

  8. 8. What is Proxy used for?

    Correct answer: To intercept operations on an object: reads, writes, deletions

    Traps such as get, set, has and deleteProperty let you implement reactivity (that's how Vue 3 works), validation, logging and default values. Reflect provides the default behavior of operations for use inside traps.

  9. 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. 10. Which scenario typically causes a memory leak in an SPA?

    Correct answer: Handlers on window and timers that aren't removed when leaving the page

    A 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. 11. Why are you advised to be careful with WeakRef and FinalizationRegistry?

    Correct answer: Garbage collection timing is unpredictable - logic shouldn't depend on it

    An object behind a WeakRef can 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. 12. What doesn't code inside a Web Worker have?

    Correct answer: Access to the DOM; it talks to the main thread via postMessage

    A 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. 13. Why pass an ArrayBuffer to 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 byteLength becomes 0. True shared memory is SharedArrayBuffer with Atomics, but it requires cross-origin isolation (COOP/COEP headers).

  14. 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. 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. 16. What must you check in a message handler when talking to an iframe via postMessage?

    Correct answer: event.origin - that the message came from the expected domain

    postMessage works across origins, and any window can send a message. Without checking origin, an attacker can send forged commands. When sending, specify a concrete targetOrigin instead of '*'. Between tabs of the same site, BroadcastChannel is handy.

  17. 17. How do you implement the observer pattern with browser APIs, without libraries?

    Correct answer: With EventTarget and CustomEvent: dispatchEvent and addEventListener

    You can extend a class from EventTarget and dispatch new CustomEvent('change', { detail }). Other built-in observers: MutationObserver (DOM changes), IntersectionObserver, ResizeObserver. Object.observe was removed from the standard.

  18. 18. Why is ResizeObserver better than a window.resize handler 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. ResizeObserver tracks the element itself and is called in the rendering cycle, without polling getBoundingClientRect. Useful for charts and virtualized lists.

  19. 19. What does a tagged template do?

    const q = sql`SELECT * FROM users WHERE id = ${id}`;

    Correct answer: Calls the sql function with an array of string parts and the substituted values

    The tag function receives strings and the values separately, so it can safely escape substitutions or pass them as query parameters - protection against injections. That's how styled-components, graphql tags and String.raw work.

  20. 20. In what order will Object.keys return 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.keys doesn't return). If order matters for numeric keys, use a Map.

  21. 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.freeze is shallow, and Object.seal only prevents adding and removing properties. Recursion walks the tree; for circular references, keep visited objects in a WeakSet. freeze has no deep option.

  22. 22. How do you serialize an object with circular references to JSON?

    Correct answer: Via a replacer in JSON.stringify, tracking visited objects in a WeakSet

    JSON.stringify throws TypeError: Converting circular structure to JSON. In a replacer you can skip already-seen objects or replace them with a marker reference (as libraries like flatted do). For copying within JS, structuredClone works - it supports cycles.

  23. 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.all starts 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-limit and similar.

  24. 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. 25. Why is it important to preserve this and 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 reach fn with the same this and arguments. That's why a regular function is returned (it has its own this), and inside the timer an arrow preserves it.

  26. 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. 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). async doesn't create a new thread: a synchronous loop inside still blocks. Cut the work into pieces and yield via setTimeout, scheduler.yield() (where supported) or requestIdleCallback; move heavy computation to a Web Worker.

  28. 28. Why is performance.now() better than Date.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 are performance.mark() and measure().

  29. 29. What does new Date(2025, 1, 1).getMonth() return, and which month is it?

    Correct answer: 1 - February

    Months in Date are zero-based, while days start at one. It's a common source of bugs along with time zones and Date mutability. Use Intl.DateTimeFormat for formatting; the Temporal API is replacing Date.

  30. 30. What happens with 10n + 1?

    Correct answer: TypeError: you can't mix BigInt and Number in arithmetic

    Implicit mixing is forbidden to avoid losing precision. Be explicit: 10n + BigInt(1) or Number(10n) + 1. BigInt is needed for integers larger than Number.MAX_SAFE_INTEGER (2^53 − 1): IDs, cryptography. JSON.stringify doesn't support it.

  31. 31. Why does 9007199254740993 === 9007199254740992 return true?

    Correct answer: Numbers above MAX_SAFE_INTEGER can't be represented exactly

    A 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 with Number.isSafeInteger.

  32. 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. 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.prototype

    A naive merge assigns target.__proto__.isAdmin = true, and ({}).isAdmin becomes true across the whole app. Protection: skip __proto__, constructor, prototype, use Object.create(null) or Map for dictionaries, validate input with a schema.

  34. 34. Why are eval and new Function usually 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, eval hinders engine optimizations. There's almost always an alternative: JSON.parse, a function table, Function with code known at build time.

  35. 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 a const before initialization

    Modules execute in graph order; with a cycle, one of them starts running while the other's export is still in the TDZ. With var you'd get undefined; with const/let/classes, an error. The fix is to move shared code into a third module or access the import lazily inside functions.

  36. 36. How does top-level await in a module affect the modules that import it?

    Correct answer: Their execution waits until the module with await finishes initializing

    A module with top-level await becomes an async node of the graph, and dependent modules run after it. Handy for loading configuration, but a slow await delays the whole branch of the app.

  37. 37. What does Promise.withResolvers() (ES2024) give you?

    Correct answer: Returns { promise, resolve, reject } for control from outside

    Previously you wrote a "deferred" for this: declared variables and assigned resolve/reject inside the constructor. Handy when a promise is resolved from elsewhere - for example, from an event handler or a queue.

  38. 38. What does new Set([1, 2, 3]).intersection(new Set([2, 3, 4])) return?

    Correct answer: Set {2, 3}

    Since 2024, Set has set-theory methods: union, intersection, difference, symmetricDifference, isSubsetOf and more. Previously this was written by hand with filter. Check target browser support before using it in production.

  39. 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 typical reduce for grouping. The result is an object with a null prototype. If keys aren't strings, use Map.groupBy.

  40. 40. What is MutationObserver useful 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 use Proxy; for localStorage, the storage event.

  41. 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

    localStorage is 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 and Blobs and supports transactions and indexes; it's easier to use via wrappers like idb.

  42. 42. How do you sync data between tabs of the same site?

    Correct answer: With BroadcastChannel or the storage event

    BroadcastChannel('app') delivers messages to all contexts of the same origin (tabs, iframes, workers). The storage event fires in other tabs when localStorage is written. sessionStorage is isolated per tab.

  43. 43. Why cache Intl.NumberFormat instances?

    Correct answer: Creating a formatter is expensive, while calling it is cheap

    Intl constructors load locale data and parse options. Calling toLocaleString() in a loop over thousands of rows creates a formatter every time. Better to create new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) once and call format.

  44. 44. What's the right way to build a query string from a params object?

    Correct answer: With new URLSearchParams(params).toString()

    URLSearchParams correctly encodes spaces, non-ASCII characters and special characters like &, which would break the request or allow parameter tampering with manual concatenation. The URL object lets you work with the whole address: url.searchParams.set('page', 2).

  45. 45. What does the expression return?

    const obj = {
      [Symbol.toPrimitive](hint) {
        return hint === "number" ? 42 : "obj";
      },
    };
    console.log(+obj, `${obj}`);

    Correct answer: 42 obj

    When converting to a primitive, the engine calls Symbol.toPrimitive with the hint 'number', 'string' or 'default'. Without it, valueOf and toString are used. This is how, for example, date subtraction works: date2 - date1.

  46. 46. What does [1, 2, 3, 4].findLast(n => n % 2 === 1) return?

    Correct answer: 3

    findLast and findLastIndex (ES2023) search from the end of the array - without reverse, which mutates the array. For multiple matches, use filter.

  47. 47. Why pass the cause option to Error?

    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 cause keeps the low-level error with its stack. DevTools and many monitoring systems show the whole chain of causes.

  48. 48. What is the Temporal Dead Zone for default parameters?

    function f(a = b, b = 1) { return a; }
    f();

    Correct answer: ReferenceError: parameter b isn't initialized yet when a is evaluated

    Parameters 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. 49. What is globalThis useful for?

    Correct answer: Uniform access to the global object in any environment

    In the browser the global object is window, in workers self, in Node.js global. globalThis works everywhere, which matters for universal (isomorphic) code and libraries.

  50. 50. Why shouldn't you pass an async function as the executor in new Promise(async (resolve) => ...)?

    Correct answer: An error after await won't reject the promise - it hangs

    The constructor ignores the promise returned by an async executor, so an exception after await becomes an unhandled rejection, and the outer promise stays pending. If there's already an await inside, the new Promise wrapper usually isn't needed at all - an async function is enough.

  51. 51. How do you abort a fetch after 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 with any()

    fetch has no timeout option. AbortSignal.timeout rejects with a TimeoutError, while a manual abort gives an AbortError, so you can tell them apart.

  52. 52. What do iterator helpers like map.values().filter(...).take(3) give you?

    Correct answer: Lazy, chainable operations on any iterator

    Iterator.prototype gained map, filter, take, drop, flatMap, reduce, toArray and more. They process items on demand, so take(3) on a huge or infinite generator stops early.

  53. 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, and new Promise(r => r(fn())) is verbose. Promise.try runs synchronously but still gives uniform error handling.

  54. 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 name

    Named groups make regexes self-documenting and robust to reordering. In replace you reference them as $<month>.

  55. 55. What does Promise.any reject with when all promises reject?

    Correct answer: An AggregateError with all rejection reasons

    Since it waits for the first success, failure means "everything failed", so all reasons are kept. Check err instanceof AggregateError to log them.

  56. 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. 57. When is requestIdleCallback appropriate?

    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. Pass timeout to guarantee it runs eventually on busy pages.

  58. 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/export lets bundlers prove a binding is unused. CommonJS require and top-level side effects (polyfills, global registration) force the module to be kept.

  59. 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, MessageChannel or scheduler.yield() to give rendering a chance.

  60. 60. What does Object.is(-0, 0) return, and why does it exist?

    Correct answer: false - it tells -0 from +0

    React and other libraries use Object.is to compare state. === says -0 === 0 and NaN !== NaN.

  61. 61. What does Symbol.toPrimitive control?

    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 calls valueOf and toString in an order depending on the hint.

  62. 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. 63. Why use Reflect.get(target, key, receiver) inside a Proxy get trap?

    Correct answer: It keeps the correct receiver, so getters see the proxy as this

    Returning target[key] calls getters with this === target, bypassing the proxy (and its tracking). Vue's reactivity uses Reflect for this reason.

  64. 64. Why do schedulers (e.g. React's) use MessageChannel instead of setTimeout(fn, 0)?

    Correct answer: A message schedules a macrotask without timer clamping

    Nested setTimeout calls 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. 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. 66. What do Trusted Types enforce?

    Correct answer: Sinks like innerHTML accept only values from an approved policy

    Enabled via CSP require-trusted-types-for 'script', they turn DOM XSS into a reviewable set of policies. Frameworks like Angular support them.

  67. 67. How does SameSite=Lax on a session cookie help against CSRF?

    Correct answer: The cookie is sent cross-site only on top-level GET navigations

    Browsers default to Lax when unspecified. Strict also blocks cross-site navigations; None requires Secure. CSRF tokens are still advised for sensitive actions.

  68. 68. What does the integrity attribute 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. crossorigin is needed so the browser can read the response to verify it.

  69. 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 fetch or new Worker resolve against the page, not the module. import.meta.url gives the module's own URL.

  70. 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 bundler

    Import maps map names to URLs and can also scope versions. They are used for no-build setups and micro-frontends sharing dependencies.

  71. 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 rules

    Default sort compares UTF-16 code units, so "Ä", "ї" or uppercase letters end up in wrong places. numeric: true also sorts "item2" before "item10".

  72. 72. Why use Intl.PluralRules for 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 distinguishes one/other. i18n libraries build on it.

  73. 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.DateTimeFormat with timeZone formats for display; the Temporal API adds explicit time-zone-aware types.

  74. 74. What does a toJSON method 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.stringify uses its return value instead of the object

    Date uses toJSON to output ISO strings. For parsing back, pass a reviver to JSON.parse - classes aren't restored automatically.

  75. 75. Is Array.prototype.sort stable 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.