JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)
What are the possible reasons for memory leaks?
Memory leaks can lead to poor performance, slow loading times and even crashes in web applications. Some of the common causes of memory leaks are listed below,
- The execessive usage of global variables or omitting the
varkeyword in local scope. - Forgetting to clear the timers set up by
setTimeoutorsetInterval. - Closures retain references to variables from their parent scope, which leads to variables might not garbage collected even they are no longer used.
Practical Code Example
javascript
// Possible Reasons for Memory Leaks:
// 1. Forgotten timers or callbacks:
// setInterval(() => { /* references heavyObj */ }, 1000);
// 2. Detached DOM elements retained in JS variables:
let detachedBtn = document.getElementById('btn');
document.body.removeChild(detachedBtn); // Still in memory via detachedBtn reference!
// 3. Accidental global variables (window.data = hugeCache)