JavaScript Middle 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. What does this code print?

    const user = {
      name: "Ann",
      greet() { return this.name; },
    };
    const greet = user.greet;
    console.log(greet());

    Correct answer: undefined (or an error in strict mode): the context is lost

    this is determined by how a function is called, not where it's declared. greet() is called without an object before the dot, so this is undefined in strict mode (the global object in sloppy mode). Fix it with user.greet.bind(user) or by calling user.greet().

  2. 2. How do call, apply and bind differ from each other?

    Correct answer: call/apply invoke immediately, bind returns a new function

    fn.call(ctx, a, b) and fn.apply(ctx, [a, b]) invoke immediately with the given this. fn.bind(ctx, a) returns a function with a permanently bound context and partially applied arguments. None of them affect arrow functions: they have no own this.

  3. 3. What does this code print?

    function f() { return this.x; }
    const g = f.bind({ x: 1 }).bind({ x: 2 });
    console.log(g());

    Correct answer: 1

    A bound function "remembers" its context forever; a second bind can't change it (though it can add arguments). Only new can override this of a bound function.

  4. 4. What does this code print after a second?

    const timer = {
      seconds: 10,
      start() {
        setTimeout(function () { console.log(this.seconds); }, 1000);
      },
    };
    timer.start();

    Correct answer: undefined: a regular callback function has its own this

    The timer calls the callback without a context, so this isn't timer. An arrow function () => console.log(this.seconds) would take this from start and print 10. This is the classic case where arrows are useful.

  5. 5. What does this code print?

    const obj = {
      name: "Ann",
      hi: () => this.name,
    };
    console.log(obj.hi());

    Correct answer: undefined: the arrow takes this from the outer scope, not the object

    An object literal doesn't create its own scope for this. The arrow takes this from the module or global scope. That's why object methods are declared with the regular hi() {} syntax.

  6. 6. How does the engine look up a property the object itself doesn't have?

    Correct answer: It walks up the prototype chain until it finds the property or reaches null

    Every object has a hidden [[Prototype]] link (Object.getPrototypeOf). That's how arrays get map from Array.prototype and all objects get toString from Object.prototype. Scope lookup applies to variables, not properties.

  7. 7. What does Object.create(proto) do?

    Correct answer: Creates a new empty object whose prototype is proto

    The properties of proto aren't copied - they're accessible through the prototype chain. Object.create(null) creates an object with no prototype at all: a handy "clean" dictionary without inherited keys like toString.

  8. 8. What are classes in JavaScript really?

    Correct answer: Syntax on top of prototypal inheritance with a few extra checks

    Class methods go into Class.prototype, and extends builds the prototype chain. But there are differences from constructor functions: a class can't be called without new, its body runs in strict mode, methods are non-enumerable, and there are private #x fields and static.

  9. 9. Why must a subclass constructor call super() before accessing this?

    Correct answer: The parent constructor creates the object; before super(), this doesn't exist yet

    In a derived class, the instance is created by the parent constructor, so accessing this before super() throws a ReferenceError. The parent's methods aren't copied - they're available through the prototype.

  10. 10. How does #count differ from _count in a class?

    Correct answer: #count is a truly private field: there's no access to it from outside

    An underscore is a convention; the property is still accessible. Private # fields are enforced by the engine: accessing obj.#count from outside is a syntax error. You can check for presence with #count in obj.

  11. 11. How does obj instanceof Class work?

    Correct answer: It checks whether Class.prototype is in the prototype chain of obj

    That's why instanceof can give surprising results when prototypes are swapped or for objects from another iframe (they have a different Array.prototype). For arrays, Array.isArray is more reliable.

  12. 12. What does this code print?

    for (var i = 0; i < 3; i++) {
      setTimeout(() => console.log(i), 0);
    }

    Correct answer: 3 3 3

    var creates one variable for the whole function, and by the time the timers fire, the loop has finished with i = 3. With let, each iteration gets a new binding and the output is 0 1 2.

  13. 13. What was an IIFE (function () { ... })() used for in the past?

    Correct answer: To create an isolated scope and avoid polluting the global one

    Before let/const and modules, a function was the only way to hide variables. An IIFE created a private scope (the "module" pattern). Today ES modules and blocks solve this, and IIFEs are sometimes used for top-level async code.

  14. 14. What is currying?

    const add = a => b => a + b;
    add(2)(3); // 5

    Correct answer: Turning a function of many arguments into a chain of single-argument functions

    Currying relies on closures: each function remembers the argument passed to it. It lets you create specialized functions (const add10 = add(10)). Partial application (bind with arguments) is a close but not identical idea.

  15. 15. How does debounce differ from throttle?

    Correct answer: Debounce waits for a pause in events, throttle calls at most once per period

    Debounce suits search-as-you-type: the request goes out when the user stops typing. Throttle suits scroll and resize: the handler runs regularly but at a limited rate. Both are implemented via a closure with a timer.

  16. 16. What is memoization?

    Correct answer: Caching a function's results by arguments to avoid recomputing them

    A memoized function keeps an "arguments → result" Map in a closure. It works for pure functions. Downsides are memory growth and the difficulty of keys for objects (WeakMap is often used).

  17. 17. How does Promise.all behave if one of the promises rejects?

    Correct answer: It rejects immediately with that error; the other results are lost

    Promise.all is "all or nothing". The other operations aren't cancelled; their results are just no longer needed. If all outcomes matter, use Promise.allSettled; for the first success, Promise.any; for the first settled, Promise.race.

  18. 18. What does Promise.allSettled return?

    Correct answer: An array of { status, value | reason } objects, one per promise

    allSettled never rejects: it waits for all promises and describes each outcome ('fulfilled' or 'rejected'). Handy when you need to run independent requests and show a partial result.

  19. 19. How does Promise.any differ from Promise.race?

    Correct answer: any waits for the first success, race for the first settled with any outcome

    Promise.any rejects only if all of them reject, with an AggregateError. Promise.race adopts the outcome of the fastest - that's how timeouts are done: Promise.race([fetch(url), timeout(5000)]).

  20. 20. How long will this code take if each request lasts 1 second?

    for (const id of [1, 2, 3]) {
      await fetchUser(id);
    }

    Correct answer: ~3 seconds: the requests run sequentially

    Each await waits for completion before the next iteration. If the requests are independent, run them in parallel: await Promise.all(ids.map(fetchUser)) - about 1 second. Sequential order is needed when the next step depends on the previous one.

  21. 21. Why doesn't forEach wait for async callbacks?

    items.forEach(async (item) => { await save(item); });
    console.log("done");

    Correct answer: forEach ignores the returned promises - "done" is printed immediately

    The callback returns a promise, but forEach doesn't use it. You need for...of with await (sequential) or await Promise.all(items.map(save)) (parallel).

  22. 22. What does the chain print?

    Promise.resolve(1)
      .then(x => x + 1)
      .then(x => { throw new Error(String(x)); })
      .catch(e => e.message)
      .then(x => console.log(x));

    Correct answer: 2

    The value returned from then is passed along. An error skips then handlers until the nearest catch, and catch returns a normal value ('2'), after which the chain continues as fulfilled.

  23. 23. What does a promise's .finally() do?

    Correct answer: Runs on any outcome and doesn't change the chain's result

    finally receives no arguments and passes the value or error through unchanged - handy for hiding a loading indicator. Exception: if the callback itself throws or returns a rejected promise, the chain rejects.

  24. 24. In what order are the lines printed?

    async function f() {
      console.log("A");
      await null;
      console.log("B");
    }
    f();
    console.log("C");

    Correct answer: A C B

    An async function's body runs synchronously until the first await. The rest continues as a microtask after the current synchronous code finishes. So first A, then C, then B.

  25. 25. Why is a recursive setTimeout sometimes preferable to setInterval?

    Correct answer: It guarantees a pause between the end of one run and the start of the next

    setInterval schedules runs on a fixed timetable: if a task (like a request) takes longer than the interval, calls overlap. A recursive setTimeout schedules the next run after the current one finishes and lets you vary the delay. Both timers are imprecise and depend on thread load.

  26. 26. What is requestAnimationFrame for?

    Correct answer: To run code before the next repaint - for smooth animations

    The callback is synced with the screen refresh rate and isn't called in background tabs, saving resources. Animation via setTimeout(fn, 16) can drift out of sync with frames and stutter.

  27. 27. What does a generator function do?

    function* ids() {
      let id = 1;
      while (true) yield id++;
    }
    const gen = ids();
    gen.next().value; // 1

    Correct answer: Returns an iterator and runs in steps, pausing at yield

    Calling a generator doesn't run its body; it returns an object with a next() method. Each next() continues until the next yield. Generators are handy for lazy and infinite sequences and for implementing iterators.

  28. 28. What does your own object need to work with for...of and spread?

    Correct answer: Implement a [Symbol.iterator]() method that returns an iterator

    The iteration protocol: [Symbol.iterator] returns an object with next() that yields { value, done }. The easiest implementation is a generator. Objects with length are array-likes: they don't work with for...of and are converted with Array.from.

  29. 29. What is Symbol used for?

    Correct answer: For unique property keys that don't clash with others

    Symbol('id') is always unique, and symbol keys don't show up in for...in or Object.keys. Built-in "well-known" symbols customize object behavior: Symbol.iterator, Symbol.toPrimitive, Symbol.asyncIterator.

  30. 30. How does WeakMap differ from Map?

    Correct answer: Keys are objects that don't block garbage collection

    If there are no other references to a key object, the entry disappears with it. That's why WeakMap has no size or iteration. Uses: private data for objects, a metadata cache for DOM nodes without memory leaks.

  31. 31. Why is structuredClone(obj) better than JSON.parse(JSON.stringify(obj))?

    Correct answer: It keeps Date, Map, Set, circular references and doesn't lose undefined

    The JSON trick turns Date into a string, loses undefined, Map, Set, Infinity and fails on cycles. structuredClone supports more types but doesn't copy functions, DOM nodes or class prototypes - such objects throw or lose their methods.

  32. 32. What does this code print?

    const cfg = Object.freeze({ db: { host: "a" } });
    cfg.db.host = "b";
    console.log(cfg.db.host);

    Correct answer: "b": freeze is shallow; the nested object isn't frozen

    Object.freeze prevents adding, removing and changing properties of the object itself only. Nested objects remain mutable. Deep freezing is done with a recursive function.

  33. 33. What does Object.defineProperty(obj, 'id', { value: 1, writable: false }) give you?

    Correct answer: The property can't be overwritten; by default it's also non-enumerable

    Every property has writable, enumerable and configurable flags. With defineProperty, unspecified flags default to false, so the property won't appear in Object.keys and can't be deleted. Getters and setters are defined this way too.

  34. 34. What does [10, 1, 2].sort() return?

    Correct answer: [1, 10, 2]

    Without a compare function, sort compares elements as strings, and '10' < '2'. For numbers you need sort((a, b) => a - b). Also, sort mutates the array; the non-mutating version is toSorted().

  35. 35. What do parseInt('12px') and Number('12px') return?

    Correct answer: 12 and NaN

    parseInt reads a number from the start of the string while it sees digits, while Number requires the whole string to be a number. Specify the radix: parseInt(str, 10). For decimals, use parseFloat.

  36. 36. How do ES modules differ from CommonJS?

    Correct answer: Imports are static and analyzed ahead of time; exports are "live" bindings

    import/export are known before execution, which lets bundlers remove unused code (tree-shaking). An imported value reflects the export's current value. require runs at runtime and copies module.exports. ESM is always in strict mode and supports top-level await.

  37. 37. Why do you need dynamic import()?

    Correct answer: To load a module on demand and split it into a separate chunk

    const { Chart } = await import('./chart.js') returns a promise of the module. Bundlers create a separate file that loads only when needed - the basis of code splitting and React.lazy. The module is cached and runs once.

  38. 38. Will fetch reject the promise on a 404 response?

    Correct answer: No: you have to check the status yourself via res.ok

    An HTTP error response is still a response. You need an explicit check: if (!res.ok) throw new Error(res.status). The promise rejects on network failure, CORS blocking or cancellation via AbortController.

  39. 39. How do you cancel a fetch request?

    Correct answer: Pass a signal from an AbortController and call controller.abort()

    After abort(), the promise rejects with an AbortError. The same signal can be passed to several requests and to addEventListener. For a timeout there's AbortSignal.timeout(5000). Promises have no cancel method.

  40. 40. What is CORS?

    Correct answer: A mechanism by which a server allows the browser to make requests from another origin

    Under the same-origin policy, the browser doesn't let a script read responses from another domain unless the server sends Access-Control-Allow-Origin. For "non-simple" requests, a preflight OPTIONS is sent first. It's a browser restriction: curl or a server don't apply it.

  41. 41. Why is a cookie with the HttpOnly flag safer than a regular one?

    Correct answer: It can't be read from JavaScript, so XSS can't steal its value

    HttpOnly blocks access via document.cookie. Session cookies also get Secure (HTTPS only) and SameSite (CSRF protection). That's why session tokens are safer in such cookies than in localStorage.

  42. 42. How does stopPropagation differ from stopImmediatePropagation?

    Correct answer: The second also prevents other handlers on the same element from running

    stopPropagation stops propagation to other elements, but the remaining handlers on the current element still run. stopImmediatePropagation stops them too. Only preventDefault cancels the default action. Don't overuse stopping propagation - it breaks delegation.

  43. 43. What does the { passive: true } option in addEventListener('touchmove', ...) do?

    Correct answer: Promises not to call preventDefault, so scrolling doesn't wait

    The browser doesn't know in advance whether a handler will cancel scrolling, so it waits for it to run. A passive handler lets scrolling start immediately - noticeably smoother on mobile. For a one-time handler there's once; for the capturing phase, capture.

  44. 44. How do you efficiently insert 1000 elements into the DOM?

    Correct answer: Collect them in a DocumentFragment (or one array) and insert in a single operation

    Each insertion into the live DOM can trigger style and layout recalculation. A fragment is built outside the document and inserted at once; el.append(...nodes) works the same way. innerHTML += in a loop reparses all the markup each time and loses handlers.

  45. 45. What's the most convenient way to detect that an element entered the viewport?

    Correct answer: With IntersectionObserver

    IntersectionObserver asynchronously reports when an element intersects the viewport, without loading the main thread on every scroll. Uses: lazy loading, infinite feeds, impression analytics. MutationObserver tracks DOM changes, not visibility.

  46. 46. What's the right way to create a custom error class?

    class ValidationError extends Error {
      constructor(message, field) {
        super(message);
        this.name = "ValidationError";
        this.field = field;
      }
    }

    Correct answer: Extend Error, call super(message) and set name

    Extending Error gives you a stack trace, correct instanceof behavior and console output. You can throw anything, but a plain object has no stack. For chaining causes there's new Error('msg', { cause: err }).

  47. 47. What does Object.fromEntries(Object.entries({ a: 1, b: 2 }).map(([k, v]) => [k, v * 10])) return?

    Correct answer: { a: 10, b: 20 }

    Object.entries turns an object into an array of pairs that array methods work with, and Object.fromEntries collects pairs back into an object. This is the standard way to "map over an object". For grouping there's Object.groupBy.

  48. 48. How does a getter differ from a regular property?

    const user = {
      first: "Ann", last: "Lee",
      get full() { return this.first + " " + this.last; },
    };

    Correct answer: The value is computed on every user.full access, without call parentheses

    A getter looks like a property but runs a function. Without a setter, assigning user.full = ... is ignored (an error in strict mode). Getters are used for computed fields and for validation via a getter/setter pair.

  49. 49. What does Array.from({ length: 3 }, (_, i) => i * 2) return?

    Correct answer: [0, 2, 4]

    Array.from creates an array from an iterable or array-like object ({ length: 3 }), and the second argument is a mapping function. It's a handy way to generate ranges. new Array(3) creates an array with "holes" that map skips.

  50. 50. What does {} === {} return?

    Correct answer: false

    Objects are compared by reference: two literals are two different objects. Comparing contents needs your own deep-equal function or a library. This matters for useEffect dependencies and memoization in React.

  51. 51. In what order are the lines printed?

    setTimeout(() => console.log("timeout"));
    queueMicrotask(() => console.log("microtask"));
    console.log("sync");

    Correct answer: sync, microtask, timeout

    Synchronous code runs first, then the whole microtask queue (promise callbacks, queueMicrotask), and only then the next macrotask such as a timer.

  52. 52. Why does this catch not handle the rejection?

    async function load() {
      try {
        return fetchUser(); // returns a rejected promise
      } catch (e) {
        return null;
      }
    }

    Correct answer: The promise rejects after leaving the try; use return await

    Inside try, return await waits for settlement, so the rejection is thrown inside the block. Outside try/catch, plain return promise is fine.

  53. 53. How does arr.toSorted() differ from arr.sort()?

    Correct answer: toSorted returns a new array; sort sorts in place

    ES2023 added non-mutating copies: toSorted, toReversed, toSpliced and with(index, value). They are handy for React/Redux state where mutation is a bug.

  54. 54. What does "a-b-c".replace("-", "+") return?

    Correct answer: "a+b-c"

    With a string pattern, replace changes only the first match. Use replaceAll("-", "+") or a regex with the g flag to replace all.

  55. 55. Why are event handlers often written as arrow-function class fields?

    class Counter {
      count = 0;
      handleClick = () => { this.count++; };
    }
    button.addEventListener("click", counter.handleClick);

    Correct answer: Arrow functions capture this, so it survives being passed around

    A prototype method passed as a callback loses this. The trade-off: each instance gets its own copy of the function instead of sharing one on the prototype.

  56. 56. What does this code print?

    const a = { user: { name: "Ann" } };
    const b = { ...a };
    b.user.name = "Bob";
    console.log(a.user.name);

    Correct answer: "Bob"

    Spread makes a shallow copy: b.user points to the same nested object. Use structuredClone or copy each changed level: { ...a, user: { ...a.user, name: "Bob" } }.

  57. 57. What does new Array(3).map((_, i) => i) return?

    Correct answer: [ <3 empty items> ] - map skips holes

    new Array(3) creates a sparse array without elements. Use Array.from({ length: 3 }, (_, i) => i) or [...Array(3).keys()].

  58. 58. Which error does undefinedVariable.foo throw, and which null.foo?

    Correct answer: ReferenceError and TypeError

    ReferenceError means a name can't be resolved; TypeError means a value is used in a way its type doesn't allow. Checking err instanceof TypeError helps handle errors precisely.

  59. 59. What does typeof notDeclared return if notDeclared was never declared?

    Correct answer: "undefined" without an error

    typeof is the only operator safe on undeclared names, which is why typeof window !== "undefined" is used to detect the browser. It still throws for let/const in the TDZ.

  60. 60. What happens when this code runs?

    greet();
    var greet = function () { console.log("hi"); };

    Correct answer: TypeError: only the var declaration is hoisted

    Function declarations are hoisted with their body; function expressions follow the hoisting rules of the variable. With let or const you'd get a ReferenceError from the TDZ.

  61. 61. What does new User("Ann") do with a regular constructor function?

    Correct answer: Creates an object linked to User.prototype and runs User on it

    If the constructor explicitly returns an object, that object replaces this. Calling it without new makes this undefined in strict mode.

  62. 62. How does Object.assign(target, source) differ from { ...target, ...source }?

    Correct answer: Object.assign mutates target; spread creates a new object

    Both are shallow and copy only own enumerable properties. Use Object.assign({}, a, b) if you need a new object with the older API.

  63. 63. Why do you need two awaits here?

    const res = await fetch("/api/user");
    const user = await res.json();

    Correct answer: Headers arrive first; reading the body is a separate async step

    The body may still be streaming when headers are available. Check res.ok before parsing, because 4xx/5xx responses don't reject.

  64. 64. What is the easiest way to send all fields of a <form> with fetch?

    const data = new FormData(form);
    await fetch("/api/profile", { method: "POST", body: data });

    Correct answer: Pass a FormData built from the form as the body

    FormData includes files and sets the correct multipart/form-data content type with boundary. Don't set Content-Type yourself, or the boundary will be missing.

  65. 65. How do you notify other parts of the page about something with a DOM event?

    el.dispatchEvent(new CustomEvent("cart:add", { detail: { id: 7 }, bubbles: true }));

    Correct answer: Dispatch a CustomEvent with data in detail

    Set bubbles: true if ancestors should hear it. It is a lightweight way for web components and widgets to communicate without global state.

  66. 66. Which property should you use to detect the pressed key?

    Correct answer: event.key, because keyCode is deprecated

    event.key gives the character respecting layout; event.code gives the physical key ("KeyA") - useful for game controls independent of keyboard layout.

  67. 67. What does options.onSuccess?.(data) do?

    Correct answer: Calls onSuccess only if it exists

    Optional call syntax is handy for optional callbacks. It still throws if onSuccess exists but isn't a function.

  68. 68. What does config.timeout ??= 5000 do?

    Correct answer: Assigns 5000 only if config.timeout is null or undefined

    Logical assignment operators ??=, ||= and &&= assign only when needed. ||= would overwrite a legitimate 0 timeout.

  69. 69. Why convert a large list of allowed IDs to a Set before many lookups?

    Correct answer: set.has is about constant time; includes scans the array

    For one lookup it doesn't matter; for thousands inside a loop, O(n) per check turns into O(n²) overall.

  70. 70. How can a function keep private state without classes?

    function createCounter() {
      let count = 0;
      return { inc: () => ++count, get: () => count };
    }

    Correct answer: Returned functions close over count

    This factory/closure pattern predates #private fields and is still common in composables and hooks.

  71. 71. What does event.target.closest("[data-id]") return?

    Correct answer: The nearest matching ancestor or itself, or null

    In delegated handlers the click often lands on a nested <span> or icon; closest finds the item element reliably.

  72. 72. Why does el.style.width return an empty string for a width set in CSS?

    Correct answer: el.style shows only inline styles, not computed ones

    Computed styles return resolved values in pixels. Reading them forces style/layout calculation, so avoid doing it in tight loops.

  73. 73. How should money be stored to avoid 0.1 + 0.2 problems?

    Correct answer: As integers in cents, or with a decimal library

    Binary floating point can't represent most decimal fractions exactly. Integer cents (or BigInt) keep sums exact; Intl.NumberFormat formats them for users.

  74. 74. What does this code print?

    const obj = {};
    const a = { id: 1 }, b = { id: 2 };
    obj[a] = "first";
    obj[b] = "second";
    console.log(obj[a]);

    Correct answer: "second"

    Object keys are strings (or symbols); both objects become "[object Object]", so the second write overwrites the first. Use a Map for object keys.

  75. 75. What does arr.with(1, "x") return for arr = ["a", "b", "c"]?

    Correct answer: A new array ["a", "x", "c"], leaving arr as is

    with is the immutable counterpart of arr[1] = "x". It supports negative indices like at and throws RangeError for out-of-range ones.