JavaScript manages memory automatically. The engine frees objects that are no longer reachable from a set of roots (globals, the current call stack, active closures, pending callbacks, DOM tree references). Modern engines like V8 use tracing, mark-and-sweep collection with generational heaps (most objects die young), plus incremental and concurrent marking to keep pauses short. You can't trigger or time it, but you can cause leaks by keeping unwanted references alive.
let user = { name: 'Ada' };
let admin = user;
user = null; // object still reachable via admin
admin = null; // now unreachable, so eligible for collection
Cycles are fine:
function makeCycle() {
const a = {}; const b = { a }; a.b = b;
}
makeCycle(); // a and b reference each other but neither is reachable, so both are collected
Old reference-counting collectors (early IE's COM/DOM objects) leaked cycles. Tracing collectors don't.
The details differ between V8, SpiderMonkey and JavaScriptCore, but all use reachability-based tracing.
// 1. Listeners and timers that outlive their component
useEffect(() => {
const onResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', onResize);
const id = setInterval(poll, 5000);
return () => { window.removeEventListener('resize', onResize); clearInterval(id); };
}, []);
// 2. Detached DOM nodes held in JS
const cache = [];
cache.push(document.querySelector('#modal')); // node removed later but still referenced
// 3. Unbounded caches and module-level arrays
const results = new Map(); // grows forever unless you evict (LRU) or use WeakMap keyed by objects
// 4. Closures capturing more than needed
function handler(bigData) {
return () => console.log(bigData.length); // keeps all of bigData alive while handler exists
}
Also: subscriptions (stores, WebSockets, observers) never unsubscribed, and global variables created accidentally in sloppy mode.
WeakMap/WeakSet to associate data with objects without keeping them alive.WeakRef and FinalizationRegistry for advanced caches. Their timing is unspecified, so never rely on them for correctness.performance.measureUserAgentSpecificMemory() (cross-origin-isolated pages) for field monitoring.null only helps if that was the last reference.delete obj.prop is not a memory tool and can slow down property access.Spotted a mistake or a rights concern? Report an issue