Event Listener Removal
Removing a browser event listener requires passing the same callback function reference used when registering it, along with compatible registration options. The usual API is `removeEventListener()`.
Use `addEventListener()` to register a callback and `removeEventListener()` to unregister it. The callback must be the same function object, not merely another function with identical code.
This is why an inline anonymous function is difficult to remove later: you have no reference to that particular function object. Store the callback in a variable, or use a named function, when you expect to remove it.
The `capture` setting matters when removing a listener. The removal call needs to match the listener's capture mode; other options such as `once` and `passive` do not need to match for listener identity in the same way.
Removing a listener is useful when a component, subscription, or temporary interaction is no longer active. It helps prevent callbacks from running after their owning UI or behavior has been discarded.
Key points
- Use the same function reference passed to `addEventListener()`.
- Match the `capture` setting when removing the listener.
- Inline anonymous callbacks cannot normally be removed later without retaining their reference.
- Call `removeEventListener()` on the same `EventTarget` that registered the listener.
Interview questions
How do you correctly remove an event listener in JavaScript?
Call `removeEventListener()` with the same event type and the same callback function reference used by `addEventListener()`. If the listener was registered with capture enabled, the removal must use the matching capture setting. Using a newly created function will not identify the original listener.
Why doesn't this removal work: `el.addEventListener('click', () => foo()); el.removeEventListener('click', () => foo());`?
Each arrow-function expression creates a separate function object. Although the two functions contain the same code, they are different references, so the second one does not identify the listener that was registered. Store the callback in a variable or use a named function when it needs to be removed later.
Which listener options matter when calling `removeEventListener()`?
The event type and callback reference must match, and the capture setting is significant for matching the registration. Options such as `once` and `passive` do not have to be repeated with the same value to identify the listener for removal. In practice, using the same options object or explicitly matching `capture` can make the code easier to reason about.
Why is listener cleanup important in frontend applications?
A listener that is no longer needed can continue reacting to events and may retain references to related state or objects. In component-based applications, cleanup is especially important when a component is removed or recreated. Proper removal prevents stale behavior and unnecessary event handling.