Question presented to candidate: "You want to mark which DOM buttons have already been processed, so you never double-process one. If you use a regular Set to track them, and a button is later removed from the page, what happens to it in memory? What would you do differently?"
What a strong answer should cover:
- 📌 Interview term:
WeakSet— a Set-like collection holding only weak references to the objects (only real objects — never primitives) added to it — meaning the presence of an object in aWeakSetgenuinely does NOT, by itself, prevent that object from being garbage collected once nothing else references it. - 📌 Interview term: the real, direct answer to the prompt — verified directly, with a real jsdom-backed DOM: a regular
Setholds a real, STRONG reference to every element added to it — even after a button is genuinely removed from the DOM tree, theSetalone would keep it alive in memory forever, a real, classic memory-leak pattern. AWeakSetholding the same reference genuinely does NOT prevent collection. - 📌 Interview term: the real trade-off this buys — a
WeakSetis genuinely NOT iterable, has NO.size, and NO.forEach()— verified directly (typeof processedButtons.sizeis genuinely"undefined") — because if you could list its contents, that list itself would need to hold real, live references, defeating the entire weak-reference purpose. - 📌 Interview term: primitive rejection — verified directly: calling
.add("a string")on a realWeakSetgenuinely THROWS a realTypeError— only real objects (which are genuinely garbage-collectible) are allowed, since a primitive value cannot meaningfully be "weakly referenced" the way an object can. - A precise answer names the practical fix for the prompt's own scenario: a
WeakSettracking processed DOM elements genuinely self-cleans as elements are removed and eventually collected — no memory leak, and no need to ever manually.delete()an element when it is torn down.
Clarifying questions expected:
- None — this is a definitional/practical question; directly answering the prompt's own memory-lifecycle question with real, verified proof is the strong signal.
Code / implementation expected: Yes — a real, jsdom-backed demonstration of tracking DOM buttons with a WeakSet, plus real proof of the primitive-rejection and no-iteration constraints.