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.
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 lostthisis determined by how a function is called, not where it's declared.greet()is called without an object before the dot, sothisisundefinedin strict mode (the global object in sloppy mode). Fix it withuser.greet.bind(user)or by callinguser.greet().2. How do
call,applyandbinddiffer from each other?Correct answer:
call/applyinvoke immediately,bindreturns a new functionfn.call(ctx, a, b)andfn.apply(ctx, [a, b])invoke immediately with the giventhis.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 ownthis.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:
1A bound function "remembers" its context forever; a second
bindcan't change it (though it can add arguments). Onlynewcan overridethisof a bound function.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 ownthisThe timer calls the callback without a context, so
thisisn'ttimer. An arrow function() => console.log(this.seconds)would takethisfromstartand print 10. This is the classic case where arrows are useful.5. What does this code print?
const obj = { name: "Ann", hi: () => this.name, }; console.log(obj.hi());Correct answer:
undefined: the arrow takesthisfrom the outer scope, not the objectAn object literal doesn't create its own scope for
this. The arrow takesthisfrom the module or global scope. That's why object methods are declared with the regularhi() {}syntax.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
nullEvery object has a hidden
[[Prototype]]link (Object.getPrototypeOf). That's how arrays getmapfromArray.prototypeand all objects gettoStringfromObject.prototype. Scope lookup applies to variables, not properties.7. What does
Object.create(proto)do?Correct answer: Creates a new empty object whose prototype is
protoThe properties of
protoaren'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 liketoString.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, andextendsbuilds the prototype chain. But there are differences from constructor functions: a class can't be called withoutnew, its body runs in strict mode, methods are non-enumerable, and there are private#xfields andstatic.9. Why must a subclass constructor call
super()before accessingthis?Correct answer: The parent constructor creates the object; before
super(),thisdoesn't exist yetIn a derived class, the instance is created by the parent constructor, so accessing
thisbeforesuper()throws aReferenceError. The parent's methods aren't copied - they're available through the prototype.10. How does
#countdiffer from_countin a class?Correct answer:
#countis a truly private field: there's no access to it from outsideAn underscore is a convention; the property is still accessible. Private
#fields are enforced by the engine: accessingobj.#countfrom outside is a syntax error. You can check for presence with#count in obj.11. How does
obj instanceof Classwork?Correct answer: It checks whether
Class.prototypeis in the prototype chain ofobjThat's why
instanceofcan give surprising results when prototypes are swapped or for objects from another iframe (they have a differentArray.prototype). For arrays,Array.isArrayis more reliable.12. What does this code print?
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }Correct answer:
3 3 3varcreates one variable for the whole function, and by the time the timers fire, the loop has finished withi = 3. Withlet, each iteration gets a new binding and the output is0 1 2.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/constand 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. What is currying?
const add = a => b => a + b; add(2)(3); // 5Correct 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 (bindwith arguments) is a close but not identical idea.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
scrollandresize: the handler runs regularly but at a limited rate. Both are implemented via a closure with a timer.16. What is memoization?
Correct answer: Caching a function's results by arguments to avoid recomputing them
A memoized function keeps an "arguments → result"
Mapin a closure. It works for pure functions. Downsides are memory growth and the difficulty of keys for objects (WeakMapis often used).17. How does
Promise.allbehave if one of the promises rejects?Correct answer: It rejects immediately with that error; the other results are lost
Promise.allis "all or nothing". The other operations aren't cancelled; their results are just no longer needed. If all outcomes matter, usePromise.allSettled; for the first success,Promise.any; for the first settled,Promise.race.18. What does
Promise.allSettledreturn?Correct answer: An array of
{ status, value | reason }objects, one per promiseallSettlednever 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. How does
Promise.anydiffer fromPromise.race?Correct answer:
anywaits for the first success,racefor the first settled with any outcomePromise.anyrejects only if all of them reject, with anAggregateError.Promise.raceadopts the outcome of the fastest - that's how timeouts are done:Promise.race([fetch(url), timeout(5000)]).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
awaitwaits 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. Why doesn't
forEachwait for async callbacks?items.forEach(async (item) => { await save(item); }); console.log("done");Correct answer:
forEachignores the returned promises - "done" is printed immediatelyThe callback returns a promise, but
forEachdoesn't use it. You needfor...ofwithawait(sequential) orawait Promise.all(items.map(save))(parallel).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:
2The value returned from
thenis passed along. An error skipsthenhandlers until the nearestcatch, andcatchreturns a normal value ('2'), after which the chain continues as fulfilled.23. What does a promise's
.finally()do?Correct answer: Runs on any outcome and doesn't change the chain's result
finallyreceives 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. 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 BAn async function's body runs synchronously until the first
await. The rest continues as a microtask after the current synchronous code finishes. So firstA, thenC, thenB.25. Why is a recursive
setTimeoutsometimes preferable tosetInterval?Correct answer: It guarantees a pause between the end of one run and the start of the next
setIntervalschedules runs on a fixed timetable: if a task (like a request) takes longer than the interval, calls overlap. A recursivesetTimeoutschedules the next run after the current one finishes and lets you vary the delay. Both timers are imprecise and depend on thread load.26. What is
requestAnimationFramefor?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. What does a generator function do?
function* ids() { let id = 1; while (true) yield id++; } const gen = ids(); gen.next().value; // 1Correct answer: Returns an iterator and runs in steps, pausing at
yieldCalling a generator doesn't run its body; it returns an object with a
next()method. Eachnext()continues until the nextyield. Generators are handy for lazy and infinite sequences and for implementing iterators.28. What does your own object need to work with
for...ofand spread?Correct answer: Implement a
[Symbol.iterator]()method that returns an iteratorThe iteration protocol:
[Symbol.iterator]returns an object withnext()that yields{ value, done }. The easiest implementation is a generator. Objects withlengthare array-likes: they don't work withfor...ofand are converted withArray.from.29. What is
Symbolused 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 infor...inorObject.keys. Built-in "well-known" symbols customize object behavior:Symbol.iterator,Symbol.toPrimitive,Symbol.asyncIterator.30. How does
WeakMapdiffer fromMap?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
WeakMaphas nosizeor iteration. Uses: private data for objects, a metadata cache for DOM nodes without memory leaks.31. Why is
structuredClone(obj)better thanJSON.parse(JSON.stringify(obj))?Correct answer: It keeps
Date,Map,Set, circular references and doesn't loseundefinedThe JSON trick turns
Dateinto a string, losesundefined,Map,Set,Infinityand fails on cycles.structuredClonesupports more types but doesn't copy functions, DOM nodes or class prototypes - such objects throw or lose their methods.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":freezeis shallow; the nested object isn't frozenObject.freezeprevents adding, removing and changing properties of the object itself only. Nested objects remain mutable. Deep freezing is done with a recursive function.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,enumerableandconfigurableflags. WithdefineProperty, unspecified flags default tofalse, so the property won't appear inObject.keysand can't be deleted. Getters and setters are defined this way too.34. What does
[10, 1, 2].sort()return?Correct answer:
[1, 10, 2]Without a compare function,
sortcompares elements as strings, and'10' < '2'. For numbers you needsort((a, b) => a - b). Also,sortmutates the array; the non-mutating version istoSorted().35. What do
parseInt('12px')andNumber('12px')return?Correct answer:
12andNaNparseIntreads a number from the start of the string while it sees digits, whileNumberrequires the whole string to be a number. Specify the radix:parseInt(str, 10). For decimals, useparseFloat.36. How do ES modules differ from CommonJS?
Correct answer: Imports are static and analyzed ahead of time; exports are "live" bindings
import/exportare known before execution, which lets bundlers remove unused code (tree-shaking). An imported value reflects the export's current value.requireruns at runtime and copiesmodule.exports. ESM is always in strict mode and supports top-levelawait.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 andReact.lazy. The module is cached and runs once.38. Will
fetchreject the promise on a 404 response?Correct answer: No: you have to check the status yourself via
res.okAn 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 viaAbortController.39. How do you cancel a
fetchrequest?Correct answer: Pass a
signalfrom anAbortControllerand callcontroller.abort()After
abort(), the promise rejects with anAbortError. The same signal can be passed to several requests and toaddEventListener. For a timeout there'sAbortSignal.timeout(5000). Promises have nocancelmethod.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 preflightOPTIONSis sent first. It's a browser restriction: curl or a server don't apply it.41. Why is a cookie with the
HttpOnlyflag safer than a regular one?Correct answer: It can't be read from JavaScript, so XSS can't steal its value
HttpOnlyblocks access viadocument.cookie. Session cookies also getSecure(HTTPS only) andSameSite(CSRF protection). That's why session tokens are safer in such cookies than inlocalStorage.42. How does
stopPropagationdiffer fromstopImmediatePropagation?Correct answer: The second also prevents other handlers on the same element from running
stopPropagationstops propagation to other elements, but the remaining handlers on the current element still run.stopImmediatePropagationstops them too. OnlypreventDefaultcancels the default action. Don't overuse stopping propagation - it breaks delegation.43. What does the
{ passive: true }option inaddEventListener('touchmove', ...)do?Correct answer: Promises not to call
preventDefault, so scrolling doesn't waitThe 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. 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 operationEach 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. What's the most convenient way to detect that an element entered the viewport?
Correct answer: With
IntersectionObserverIntersectionObserverasynchronously reports when an element intersects the viewport, without loading the main thread on every scroll. Uses: lazy loading, infinite feeds, impression analytics.MutationObservertracks DOM changes, not visibility.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, callsuper(message)and setnameExtending
Errorgives you a stack trace, correctinstanceofbehavior and console output. You can throw anything, but a plain object has no stack. For chaining causes there'snew Error('msg', { cause: err }).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.entriesturns an object into an array of pairs that array methods work with, andObject.fromEntriescollects pairs back into an object. This is the standard way to "map over an object". For grouping there'sObject.groupBy.48. How does a
getterdiffer 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.fullaccess, without call parenthesesA 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. What does
Array.from({ length: 3 }, (_, i) => i * 2)return?Correct answer:
[0, 2, 4]Array.fromcreates 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" thatmapskips.50. What does
{} === {}return?Correct answer:
falseObjects are compared by reference: two literals are two different objects. Comparing contents needs your own deep-equal function or a library. This matters for
useEffectdependencies and memoization in React.51. In what order are the lines printed?
setTimeout(() => console.log("timeout")); queueMicrotask(() => console.log("microtask")); console.log("sync");Correct answer:
sync,microtask,timeoutSynchronous code runs first, then the whole microtask queue (promise callbacks,
queueMicrotask), and only then the next macrotask such as a timer.52. Why does this
catchnot 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; usereturn awaitInside
try,return awaitwaits for settlement, so the rejection is thrown inside the block. Outsidetry/catch, plainreturn promiseis fine.53. How does
arr.toSorted()differ fromarr.sort()?Correct answer:
toSortedreturns a new array;sortsorts in placeES2023 added non-mutating copies:
toSorted,toReversed,toSplicedandwith(index, value). They are handy for React/Redux state where mutation is a bug.54. What does
"a-b-c".replace("-", "+")return?Correct answer:
"a+b-c"With a string pattern,
replacechanges only the first match. UsereplaceAll("-", "+")or a regex with thegflag to replace all.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 aroundA 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. 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.userpoints to the same nested object. UsestructuredCloneor copy each changed level:{ ...a, user: { ...a.user, name: "Bob" } }.57. What does
new Array(3).map((_, i) => i)return?Correct answer:
[ <3 empty items> ]-mapskips holesnew Array(3)creates a sparse array without elements. UseArray.from({ length: 3 }, (_, i) => i)or[...Array(3).keys()].58. Which error does
undefinedVariable.foothrow, and whichnull.foo?Correct answer:
ReferenceErrorandTypeErrorReferenceErrormeans a name can't be resolved;TypeErrormeans a value is used in a way its type doesn't allow. Checkingerr instanceof TypeErrorhelps handle errors precisely.59. What does
typeof notDeclaredreturn ifnotDeclaredwas never declared?Correct answer:
"undefined"without an errortypeofis the only operator safe on undeclared names, which is whytypeof window !== "undefined"is used to detect the browser. It still throws forlet/constin the TDZ.60. What happens when this code runs?
greet(); var greet = function () { console.log("hi"); };Correct answer:
TypeError: only thevardeclaration is hoistedFunction declarations are hoisted with their body; function expressions follow the hoisting rules of the variable. With
letorconstyou'd get aReferenceErrorfrom the TDZ.61. What does
new User("Ann")do with a regular constructor function?Correct answer: Creates an object linked to
User.prototypeand runsUseron itIf the constructor explicitly returns an object, that object replaces
this. Calling it withoutnewmakesthisundefined in strict mode.62. How does
Object.assign(target, source)differ from{ ...target, ...source }?Correct answer:
Object.assignmutatestarget; spread creates a new objectBoth are shallow and copy only own enumerable properties. Use
Object.assign({}, a, b)if you need a new object with the older API.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.okbefore parsing, because 4xx/5xx responses don't reject.64. What is the easiest way to send all fields of a
<form>withfetch?const data = new FormData(form); await fetch("/api/profile", { method: "POST", body: data });Correct answer: Pass a
FormDatabuilt from the form as the bodyFormDataincludes files and sets the correctmultipart/form-datacontent type with boundary. Don't setContent-Typeyourself, or the boundary will be missing.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
CustomEventwith data indetailSet
bubbles: trueif ancestors should hear it. It is a lightweight way for web components and widgets to communicate without global state.66. Which property should you use to detect the pressed key?
Correct answer:
event.key, becausekeyCodeis deprecatedevent.keygives the character respecting layout;event.codegives the physical key ("KeyA") - useful for game controls independent of keyboard layout.67. What does
options.onSuccess?.(data)do?Correct answer: Calls
onSuccessonly if it existsOptional call syntax is handy for optional callbacks. It still throws if
onSuccessexists but isn't a function.68. What does
config.timeout ??= 5000do?Correct answer: Assigns 5000 only if
config.timeoutisnullorundefinedLogical assignment operators
??=,||=and&&=assign only when needed.||=would overwrite a legitimate0timeout.69. Why convert a large list of allowed IDs to a
Setbefore many lookups?Correct answer:
set.hasis about constant time;includesscans the arrayFor one lookup it doesn't matter; for thousands inside a loop, O(n) per check turns into O(n²) overall.
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
countThis factory/closure pattern predates
#privatefields and is still common in composables and hooks.71. What does
event.target.closest("[data-id]")return?Correct answer: The nearest matching ancestor or itself, or
nullIn delegated handlers the click often lands on a nested
<span>or icon;closestfinds the item element reliably.72. Why does
el.style.widthreturn an empty string for a width set in CSS?Correct answer:
el.styleshows only inline styles, not computed onesComputed styles return resolved values in pixels. Reading them forces style/layout calculation, so avoid doing it in tight loops.
73. How should money be stored to avoid
0.1 + 0.2problems?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.NumberFormatformats them for users.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 aMapfor object keys.75. What does
arr.with(1, "x")return forarr = ["a", "b", "c"]?Correct answer: A new array
["a", "x", "c"], leavingarras iswithis the immutable counterpart ofarr[1] = "x". It supports negative indices likeatand throwsRangeErrorfor out-of-range ones.