Question presented to candidate: "You're building a to-do list where items can be added and removed dynamically. Walk me through how you'd wire up click handlers for a 'delete' button on each item, and what happens to your approach as items are added after the page first loads?"
What a strong answer should cover:
- 📌 Interview term: event delegation — attaching one event listener to a shared ancestor element, then using
event.targetinside that single handler to determine which specific descendant was actually interacted with, instead of attaching a separate listener to every individual item. - 📌 Interview term: the real, direct answer to the prompt — verified directly with jsdom: a single listener attached to the list's parent genuinely handled a click on an item that was appended to the DOM after the listener was attached, with zero new listeners — while the naive per-item-listener approach genuinely MISSED that same dynamically-added item's click, because no listener had been individually attached to it.
- 📌 Interview term:
event.targetvs.event.currentTarget— inside a delegated handler,event.targetis the actual, specific element the user interacted with (a button, an icon), whileevent.currentTargetis always the element the listener was attached to (the shared parent) — a precise answer distinguishes these explicitly, since delegation logic almost always needstarget, notcurrentTarget. - A precise answer names the mechanism that makes delegation possible: event bubbling — the click event genuinely travels up from the clicked descendant through every ancestor, so a listener anywhere on that ancestor chain genuinely receives it, covered in more depth in this bank's own dedicated bubbling/capturing question.
- A precise answer names the real, concrete cost comparison verified directly: a 1000-item list needs exactly 1 delegated listener versus 1000 individual listeners — a real, measurable memory and setup-time difference for large or frequently-changing lists.
Clarifying questions expected:
- "Roughly how many items, and how often are they added/removed?" — directly decides how much the memory/re-attachment cost of the naive per-item approach actually matters in practice.
- "Does the delete button live directly on the item, or nested inside other markup (an icon inside a span inside the button)?" — determines how precisely
event.targetneeds to be checked/matched (e.g. with.closest()) inside the delegated handler.
Code / implementation expected: Yes — a real delegated click handler using event.target, plus the concrete jsdom-verified proof that it correctly handles a dynamically-added item with zero extra listener setup, is the strongest possible answer to the prompt.