Chapter 10 of 12
10.1 Memory Management & Garbage Collection
Engine garbage collectors allocate and automatically free memory using algorithms like Mark-and-Sweep. Memory leaks happen when unused objects remain reachable in the root reference tree.
Common Memory Leak Causes
1. Accidental Global Variables (attaching to window/globalThis)
2. Uncleared Timers (setInterval retaining closed variables)
3. Detached DOM Nodes (storing DOM references in arrays after removal)
4. Forgotten Event Listeners
10.2 Performance Optimization: Debounce vs Throttle
Debounce and Throttle Implementationjavascript
// Debounce: Delays execution until user stops triggering event for N ms
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// Throttle: Guarantees execution at most once every N ms
function throttle(fn, limit) {
let inThrottle;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}10.3 Web Security Best Practices
Always sanitize untrusted user inputs to prevent Cross-Site Scripting (XSS). Never use innerHTML with raw input; use textContent or DOMPurify.