Middle
What do you know about garbage collection in JavaScript? What are memory leaks and in what cases can they occur?
sobes.tech AI
Answer from AI
Garbage Collector in JavaScript automatically frees memory occupied by objects that are no longer accessible from the code. It tracks objects that have no references and deletes them to prevent memory overflow.
Memory leaks occur when objects remain in memory even though they are no longer needed, due to lingering references. This leads to increased memory consumption and can slow down the application.
Common causes of leaks:
- Global variables that are not cleared.
- Closures holding references to large objects.
- Event listeners that are not removed after use.
- Caching data without size limits.
Example of a leak through a listener:
function setup() {
const element = document.getElementById('button');
element.addEventListener('click', () => {
// handler
});
}
// If the element is removed from the DOM but the listener is not removed, memory will not be freed
To prevent leaks, it is important to remove listeners, clear references, and monitor the lifecycle of objects.