JavaScript Memory Management: How Garbage Collection Really Works
You do not malloc and free in JavaScript, but you can still leak. Here is the mental model that prevents leaks. JavaScript is garbage collected, which means you do not manually allocate and free memory. This does not mean memory leaks are impossible; it means leaks happen through references the collector cannot prove are dead. Understanding how the collector decides what to free is the difference between code that holds steady and code whose memory creeps upward until the tab crashes. Reachability Is Everything The garbage collector frees objects that are no longer reachable from a set of roots: global variables, the call stack, and registered event listeners. An object stays alive as long as there is any path of references from a root to it. A leak is a reference path you forgot about: a closure capturing a large object, a Map keyed by objects that never leave, an event listener you never removed. The Closure Capture Leak Closures keep their outer variables alive. If a long-lived closure captures a large object even though it only uses one small field, the entire object remains reachable and cannot be collected. I…