Question presented to candidate: "You call addEventListener with an anonymous arrow function, and later try to remove it with removeEventListener passing a new arrow function with the exact same code inside it. Does the listener actually get removed?"
What a strong answer should cover:
- 📌 Interview term: reference-based comparison —
removeEventListeneridentifies which listener to remove by comparing the function reference (identity) passed to it against the reference originally passed toaddEventListener— it does not compare function bodies/source code at all. - 📌 Interview term: the direct, verified answer to the prompt — verified directly: removing with the exact same function reference genuinely succeeded (0 clicks fired afterward), while removing with a different function reference that has an identical body genuinely failed silently — no error was thrown, and the original listener genuinely kept firing.
- 📌 Interview term: the anonymous-function trap — verified directly: an anonymous arrow function passed inline to
addEventListenercan never be removed later, because there is no way to reference that exact original function again — passing a newly created arrow function (even with identical code) toremoveEventListenergenuinely fails to match it. - A precise answer names the real, standard fix: store the handler in a named variable (or a class/component method) so the identical reference can be passed to both
addEventListenerandremoveEventListener. - A precise answer names the real, practical consequence: this is a common, genuine source of memory leaks and duplicate-handler bugs, especially in single-page apps and frameworks where components mount/unmount repeatedly and forget to correctly clean up their own listeners.
Clarifying questions expected:
- None — this is a definitional/technical question; directly answering the prompt's own scenario with the verified proof is the strong signal.
Code / implementation expected: Yes — the same-reference-succeeds vs. different-reference-fails contrast is the clearest, most convincing demonstration.