JavaScript · DOM · Junior · Best Practice
What is event delegation and when should you use it?
Short Interview Answer
Attach one listener to a common ancestor and use `event.target` to handle children — efficient for many dynamic elements.
Detailed Explanation
Instead of binding N listeners to N rows, bind one on the table/list and switch on closest matching selector. Benefits: less memory, works for elements added later, simpler teardown. Caveats: some events don't bubble (historically `focus` — use capture/`focusin`), and checks must be careful with nested interactive elements. Delegation is standard for large lists and component roots.
Example
list.addEventListener('click', (e) => {
const btn = e.target.closest('button.delete');
if (!btn || !list.contains(btn)) return;
deleteRow(btn.dataset.id);
});Interview Tip
Use `closest` in the example — modern best practice.
Common Mistake
Delegating non-bubbling events without capture/`focusin`.