Skip to content

Commit 834bc7c

Browse files
committed
Purpose of removing event listeners
1 parent 76d10a2 commit 834bc7c

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9148,6 +9148,31 @@ Common use cases and benefits:
91489148
```
91499149
**[⬆ Back to Top](#table-of-contents)**
91509150
9151+
473. ### Why is it important to remove event listeners after use?
9152+
9153+
In JavaScript, you need to be mindful of removing event listeners to avoid memory leaks — especially in long-lived apps like single-page applications (SPAs) or when working with frameworks/libraries. Eventhough JavaScript has automatic garbage collection, memory leaks can still happen if:
9154+
9155+
1. A DOM element is removed, but a listener still references it.
9156+
2. A callback (event listener) holds a reference to a large object or closure that can't be cleaned up.
9157+
3. Global objects like window, document etc retain listeners indefinitely unless manually removed.
9158+
9159+
So if you add any event listeners to DOM element, it is a good practice to remove it after its usage as shown below,
9160+
9161+
```javascript
9162+
const button = document.getElementById("btn");
9163+
9164+
function handleClick() {
9165+
console.log("Clicked!");
9166+
}
9167+
9168+
button.addEventListener("click", handleClick);
9169+
9170+
// Always remove when done
9171+
button.removeEventListener("click", handleClick);
9172+
```
9173+
9174+
**[⬆ Back to Top](#table-of-contents)**
9175+
91519176
<!-- QUESTIONS_END -->
91529177
91539178
### Coding Exercise

0 commit comments

Comments
 (0)